【问题标题】:Modified event of FileSystemWatcher getting triggered multiple times [duplicate]FileSystemWatcher的修改事件被多次触发[重复]
【发布时间】:2019-03-06 03:37:00
【问题描述】:

我要监控以下内容

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

我使用以下代码订阅 FileSystemWatcher 类的 createdchanged 事件。我注意到 FSW 类的一些问题。

  • 在替换文件时,多次触发 changed 事件 次。

我该如何解决这个问题。请指教。

 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 

【问题讨论】:

  • 因为多处发生了变化。文件内容。文件最后修改时间。等
  • @RaymondChen 我该如何解决这个问题?请指教。
  • 哇!看到 RC 对 SO 的评论。喜欢你的博客。
  • 没有什么可修复的。 FileSystemWatcher 的行为符合设计。该文件更改了两次。
  • @RaymondChen 好吧,即使添加了watcher.NotifyFilter = NotifyFilters.LastWrite;,它的行为也没有达到预期。对于 8 个文件,该事件被触发超过 8 次。

标签: c# .net filesystemwatcher


【解决方案1】:

是的,正如 cmets 中已经提到的那样,这是预期的。 也可以看看: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.
    }

【讨论】:

  • 谢谢,但对于 8 个文件,该事件被触发了 13 次。
  • 你能在你的测试代码中实现这个吗,我相信这应该能够“返回”多个事件引发。让我知道观察结果。
  • 我通过引用帖子stackoverflow.com/a/23287926/848968中的这个答案设法解决了这个问题
  • @techno 很好,请从 Git Repo 解决方案中提取答案并将其发布在这里,谁知道该用户何时删除了该 repo。
  • 此问题已被标记为重复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2013-07-06
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多