EDIT: The problem has been resolved, see answer below.
I am having trouble accessing a FileSystemWatcher
from another method.
EDIT: More code, as requested.
public static void watch(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size;
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
// The reason for having this try block (and EnableRaisingEvents toggling) is to solve a known problem with FileSystemWatcher, in which the event is fired twice.
try
{
MessageBox.Show("File changed.");
watcher.EnableRaisingEvents = false; // Error: The name 'watcher' does not exist in the current context
}
finally
{
watcher.EnableRaisingEvents = true; //Error: The name 'watcher' does not exist in the current context
}
}
I want to change the EnableRaisingEvents
property.
I can't do that because of the scope problem. Normally what I would do is declare the FileSystemWatcher
somewhere with a bigger scope, but I can't do that here because a new one must be created every time I run the method.
So, how can I change the property of an object from a different method?
PS: I have searched around, and tried different things but ultimately nothing worked.
EDIT: Just to clarify, I MUST keep the FileSystemWatcher declaration INSIDE the method (as opposed to giving it a bigger scope, thus allowing it to be modified by another method). The reason for this is that I need a new one to be created every time I run the method.