我要监视以下内容
我使用以下代码预订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
答案 0 :(得分:0)
是的,正如评论中已经提到的那样。 还可以看看: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.
}