I want to use multiple FileSystemWatchers to watch different text files.
I am successful in creating the watchers and the file change events are being invoked and I can add the changes in the text files to a string and display this on a form.
What I want to know is how I can tell which watcher is causing the event?
Eg. watcher1, watcher2 or watcher3?
I know I can find out the path and file name of the file that has changed but this doesn't really help me.
I realize you already found your own way to do this, but I recommend you look at the sender parameter within the event that is being fired. This is common for a lot of events. Here is a small example:
private static FileSystemWatcher watcherTxt;
private static FileSystemWatcher watcherXml;
static void Main(string[] args)
{
String dir = @"C:\temp\";
watcherTxt = new FileSystemWatcher();
watcherTxt.Path = dir;
watcherTxt.Filter = "*.txt";
watcherTxt.EnableRaisingEvents = true;
watcherTxt.Created += new FileSystemEventHandler(onCreatedFile);
watcherXml = new FileSystemWatcher();
watcherXml.Path = dir;
watcherXml.Filter = "*.xml";
watcherXml.EnableRaisingEvents = true;
watcherXml.Created += new FileSystemEventHandler(onCreatedFile);
Console.ReadLine();
}
private static void onCreatedFile(object sender, FileSystemEventArgs e)
{
if (watcherTxt == sender)
{
Console.WriteLine("Text Watcher Detected: " + e.FullPath);
}
if (watcherXml == sender)
{
Console.WriteLine("XML Watcher Detected: " + e.FullPath);
}
}