【问题标题】:FileSystemWatcher event calling the more than once [duplicate]FileSystemWatcher 事件多次调用[重复]
【发布时间】:2014-05-21 11:40:12
【问题描述】:

我遇到了一个奇怪的问题。我搜索并尝试解决此问题,但其他解决方案对我不起作用。我在看一个文件夹。当在该文件夹中创建任何文件时,创建的事件会调用。但奇怪的是,它被称为该文件夹中存在的文件数。

例如:

对于第一个文件,它只调用一次(我想要的)。

对于第二个文件,它调用了两次。

对于第三个文件,它被调用了 3 次。

代码:

fw.Path = @"D:\xx\xx\" + fullName.GetStringPart(0, 3) + @"\" + fullName.GetStringPart(3, 2) + @"\" + fullName.Substring(5, 4) + @"\" + fullName;
fw.Filter = "*.*";
fw.NotifyFilter = NotifyFilters.CreationTime|
    NotifyFilters.FileName;
fw.Changed += new FileSystemEventHandler(OnFileChanged);
fw.Created += new FileSystemEventHandler(OnCreated);
fw.Deleted += new FileSystemEventHandler(OnDeleted);
fw.EnableRaisingEvents = true;

事件:

void OnCreated(object sender, FileSystemEventArgs e)
{
    try
    {
        fw.EnableRaisingEvents = false;
        while (!TestOpen(e.FullPath)) ;
        string str = e.FullPath;
        allImag.Add(str.Replace("Thumbs", "images"));
        allThumbImag.Add(e.FullPath);
        if (InvokeRequired)
            this.Invoke(new Action(() => this.addImage(e.FullPath)));
        else
            addImage(e.FullPath);
    }

    finally
    {
        fw.EnableRaisingEvents = true;
    }
}

你猜到了吗?

【问题讨论】:

  • 你能发布你的代码吗?
  • 如何创建文件?也许程序也会尝试对现有文件做一些事情?
  • 我只是在移动文件。
  • @Rashad 只是预感,您是否尝试过禁用防病毒软件?
  • 这些活动您只注册一次吗?

标签: c# .net winforms filesystemwatcher


【解决方案1】:

来自 FileSystemWatcher.Created 事件的 MSDN 文档:

常见的文件系统操作可能引发多个事件。例如,当一个文件从一个目录移动到另一个目录时,可能会引发几个 OnChanged 以及一些 OnCreated 和 OnDeleted 事件。移动文件是一个复杂的操作,由多个简单的操作组成,因此会引发多个事件。同样,某些应用程序(例如防病毒软件)可能会导致 FileSystemWatcher 检测到的其他文件系统事件。

无法保证该事件只会发生一次。这可能是由监视您的文件夹的外部进程引起的,例如某种防病毒软件。我会调查一下,因为代码看起来不错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多