Search code examples
c#filesystemwatcher

filewatcher watch several files but handle them differently


I need to watch several file at different time and sometimes at the same time.

I am using this as a test:

namespace FilewatcherTest
{
  public partial class Form1 : Form
  {
    private System.IO.FileSystemWatcher FSWatcherTest;

    public Form1()
    {
      InitializeComponent();

      FSWatcherTest = new FileSystemWatcher();
      EventHandling();
      FSWatcherTest.Path = @"d:\tmp";
      FSWatcherTest.Filter = "file.txt";
      // Begin watching.
      FSWatcherTest.EnableRaisingEvents = true;
    }

    protected void EventHandling()
    {
      FSWatcherTest.Changed += FSWatcherTest_Changed;
      FSWatcherTest.Deleted += FSWatcherTest_Deleted;
      FSWatcherTest.Renamed += FSWatcherTest_Renamed;
      FSWatcherTest.Created += FSWatcherTest_Created;
    }

    private void FSWatcherTest_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
      WriteToLog("File Changed");
    }

    private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
    {
      WriteToLog("File Created");
    }

    private void FSWatcherTest_Deleted(object sender, System.IO.FileSystemEventArgs e)
    {
      WriteToLog("File Deleted");          
    }

    private void FSWatcherTest_Renamed(object sender, System.IO.RenamedEventArgs e)
    {
      WriteToLog("File Renamed");
    }

    private void WriteToLog(string message)
    {
      using (var sw = new StreamWriter(@"d:\tmp\service.log", true))
      {
        sw.WriteLine(string.Format("{0} {1}", DateTime.Now,message));
      }

    }

  }
}

Of course I'll change the hardcoded paths once I have something in place since this is going into a service I created.

My question is, can I use the same file watcher or should I use a unique one for each file?

If I use the same one, how do I know which file is raising the event?

Thanks!!

EDIT Sorry I haven't used filesystemwatcher before and didn't know it mattered but the files will be in different directories and not of the same file type.


Solution

  • can I use the same file watcher or should I use a unique one for each file?

    In your case, I don't think there is a reason to create a new instance of FileSystemWatcher for every file you're watching. Yes, you can use the same one. You can use a filter such as "*.txt" or whatever you need to watch a set of files...

    If I use the same one, how do I know which file is raising the event?

    The FileSystemEventArgs has a Name property which returns the name of the file that triggered the event. So for example:

    private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
    {
       string fileName = e.Name; 
       WriteToLog("File Created: " + fileName);
    }