I have the following method that sets up a FileSystemEventHandler to monitor for changes to a config.xml file.
public void WatchConfigFile(???)
{
this.watcher = new FileSystemWatcher();
DirectoryInfo _di = Directory.GetParent(configFile);
this.watcher.Path = _di.FullName;
this.watcher.Filter = Path.GetFileName(configFile);
this.watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime;
this.watcher.Changed += new FileSystemEventHandler(???);
this.watcher.EnableRaisingEvents = true;
log.Info("Config watcher established at " + watcher.Path);
}
I would like to add this method to a library of standard methods we use over and over but do not know how to pass the onChanged method handler to the method and assign it to the watcher. The method represented by ??? (to handle the changes) would be something like this:
public void ConfigFileChanged(object source, FileSystemEventArgs e)
{
// Do something when file is updated
}
I would like to be able to call this as follows:
_library.WatchConfigFile(ConfgiFileChanged);
Well it sounds like you just want the handler itself as the parameter:
public void WatchConfigFile(FileSystemEventHandler handler)
{
...
this.watcher.Changed += handler;
...
}
That should be fine. There'll be a method group conversion from ConfigFileChanged
to FileSystemEventHandler
when you call WatchConfigFile
.
(Bear in mind that currently your WatchConfigFile
method replaces the current contents of this.watcher
... so if you call it twice, you won't have a reference to the first watcher any more. Perhaps you want a List<FileSystemWatcher>
instead?)
See more on this question at Stackoverflow