2

如果这是一个重复的问题,我将首先道歉。有很多 FileSystemWatcher 问题,但我没有看到任何解决我的问题的问题。

好的,所以我在 C# 中有一个控制台应用程序,它正在监视一个目录,我们将其称为Root. Root有很多子文件夹。Root此应用程序的目的是在其子文件夹或其任何子文件夹中创建、修改或删除任何 .csv 文件时写入日志文件。我目前有这个工作正常,有点。唯一的问题是,当创建、修改或删除 .csv 文件时,它实际上会引发所有 3 个事件。

例如,如果我在Rootcalled中创建一个文件test.csv,日志文件将如下所示:

 10/04/2012: File F:/Root/test.csv Created
 10/04/2012: File F:/Root/test.csv Changed
 10/04/2012: File F:/Root/test.csv Created
 10/04/2012: File F:/Root/test.csv Deleted

我不确定发生了什么,所以这是设置FileSystemWatcher

 _watchFolder.Path = ConfigurationManager.AppSettings["RootToWatch"];
 _watchFolder.Filter = ConfigurationManager.AppSettings["FileNameToWatch"];
 _watchFolder.NotifyFilter = NotifyFilters.FileName 
                             | NotifyFilters.LastWrite;
 _watchFolder.IncludeSubdirectories = true;
 _watchFolder.Changed += new FileSystemEventHandler(OnChanged);
 _watchFolder.Created += new FileSystemEventHandler(OnChanged);
 _watchFolder.Deleted += new FileSystemEventHandler(OnChanged);
 _watchFolder.Renamed += new RenamedEventHandler(OnRenamed);

 try
 {
     _watchFolder.EnableRaisingEvents = true; 
 }
 catch (ArgumentException ex)
 {
     AbortMonitoring(ex.Message);
 }

这是我的 OnChanged 事件(重命名相同但参数不同)

  protected static void OnChanged(object sender, FileSystemEventArgs e)
    {
        //compile message to insert into log file.
        string message = "File: " + e.FullPath + " " + e.ChangeType;
        UpdateLogFile(message);
    }
4

1 回答 1

0

Just add a handler only for the changed event. It should gather all change types. The other types of events like created are there if you want the event to be raised only on a particular change type.

watchFolder.IncludeSubdirectories = true;
_watchFolder.Changed += new FileSystemEventHandler(OnChanged);
于 2012-10-04T16:54:59.550 回答