这个问题在这里已有答案:
我想监控以下内容
我使用以下代码订阅FileSystemWatcher类的created
和changed
事件。我已经注意到FSW类的一些问题。
我怎么能克服这个问题。亲切的建议。
watcher.Path = watchpath;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(copied);
watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.EnableRaisingEvents = true;
对于复制到该文件夹的单个项目,将引发以下事件
*******> Created
-----> Changed
-----> Changed
是的,正如评论中已经提到的那样。另外看看:FileSystemWatcher Changed event is raised twice
要有一个解决方法,您需要添加一个字典,该字典将跟踪每个文件的引发事件。
Dictionary<string, DateTime> lastWriteDate //fileName - Last write date time
如果发生变化,你将不得不像下面那样处理它,
private static void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
string filePath = e.FullPath;
DateTime writeDate = System.IO.File.GetLastWriteTime(filePath);
if (lastWriteDate.ContainsKey(filePath))
{
if (lastWriteDate[filePath] == writeDate)
//Exit as we already have raised an event for this
return;
lastWriteDate[filePath] = writeDate;
}
else
{
lastWriteDate.Add(filePath, writeDate);
}
//Do your stuff.
}