2013-10-14 19 views
0

我已经编写了一个测试应用程序来试用来自msdn的FileSystemWatcher示例代码。FileSystemWatcher呼叫处理程序三次

它基本上可以工作,但处理程序被调用三次。有人知道为什么吗?

namespace FileWatcherTest 
{ 
    public partial class Form1 : Form 
    { 
     private FileSystemWatcher watcher; 
     public Form1() 
     { 
      InitializeComponent(); 
      string testPath = 
       Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) 
       + @"\Test"; 
      InitialiseFileWatcher(testPath, "example.txt"); 
     } 

     private void InitialiseFileWatcher(string path, string fileName) 
     { 
      watcher = new FileSystemWatcher(); 
      watcher.Path = path; 
      watcher.NotifyFilter = NotifyFilters.LastWrite; 
      watcher.Filter = fileName; 
      watcher.Changed += new FileSystemEventHandler(OnFarmListChanged); 
      // Begin watching. 
      watcher.EnableRaisingEvents = true; 
     } 

     private static void OnFarmListChanged(object source, FileSystemEventArgs e) 
     { 
      string text = "File: " + e.FullPath + " " + e.ChangeType; 
      MessageBox.Show(text); 
     } 
    } 
} 

回答

1

为链接文件的一部分,你包括:

常见的文件系统操作可能会引发多个事件。例如,当文件从一个目录移动到另一个目录时,可能会引发几个OnChanged和一些OnCreated和OnDeleted事件。移动文件是一项复杂的操作,由多个简单操作组成,因此引发多个事件。同样,某些应用程序(例如防病毒软件)可能会导致由FileSystemWatcher检测到的其他文件系统事件。