FileSystemWatcher的修改事件被多次触发[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想监控以下内容

  • 正在创建/复制到目录的新文件
  • 现有文件已编辑

我使用以下代码订阅FileSystemWatcher类的createdchanged事件。我已经注意到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 
c# .net filesystemwatcher
1个回答
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.
    }
© www.soinside.com 2019 - 2024. All rights reserved.