Below is my code for a File watcher class I wrote:
class FileWatcher
{
#region Method that begins watching
public static void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = ConfigurationManager.AppSettings["OpticusFileLoc"];
watcher.Filter = ConfigurationManager.AppSettings["OpticusFileName"];
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Changed += new FileSystemEventHandler(OnChanged);
Console.Write("\nWatcher started. Press any key to end.\n");
watcher.EnableRaisingEvents = true;
}
#endregion
#region Trigger function on change
public static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File has been changed.\n");
//watcher.EnableRaisingEvents = false ;
//Program.Main();
}
#endregion
}
How can I, from the OnChanged method, set the watcher.EnableRaisingEvents flag to false?
I guess I could do it by moving the declaration of the FileSystemWatcher object outside the method it is in, but I’m wondering if there’s another way to do it.
That’s exactly how you should do it (have
watcherjust be a member field of yourFileWatcherclass).That said, you also could do it like this:
Notice the comment I added in the code above. Generally it’s a bad call to make methods such as this
public, as this makes it possible for any arbitrary code to callOnChangedeven when doing so makes no sense. (You want for this method to capture the event of a file being changed; if it’s actually callable from anywhere, then how do you know if the file was in fact changed or if this is just some random call from elsewhere?)