1

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.

4

1 に答える 1

2

同じファイル ウォッチャーを使用できますか、それともファイルごとに一意のファイル ウォッチャーを使用する必要がありますか?

あなたの場合、監視しているすべてのファイルに対して FileSystemWatcher の新しいインスタンスを作成する理由はないと思います。はい、同じものを使用できます。「*.txt」などのフィルターを使用するか、一連のファイルを監視するために必要なものを使用できます...

同じファイルを使用する場合、どのファイルがイベントを発生させているかを知るにはどうすればよいですか?

FileSystemEventArgsには、Nameイベントをトリガーしたファイルの名前を返すプロパティがあります。たとえば、次のようになります。

private void FSWatcherTest_Created(object sender, System.IO.FileSystemEventArgs e)
{
   string fileName = e.Name; 
   WriteToLog("File Created: " + fileName);
}
于 2013-02-17T16:41:21.400 に答える