我编写了一个测试应用程序来试用msdn中的 FileSystemWatcher 示例代码。
它基本上可以工作,但处理程序被调用了 3 次。有谁知道为什么?
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);
}
}
}