FileSystemWatcher事件多次调用

时间:2014-05-21 11:40:12

标签: c# .net winforms filesystemwatcher

我有一个奇怪的问题。我搜索并试图解决这个问题,但其他解决方案对我没有用。我正在看一个文件夹。当在该文件夹中创建任何文件时,创建的事件会调用。但奇怪的是,它被称为该文件夹中存在的文件数。

例如:

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

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

对于第3个文件,它被调用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;
    }
}

有什么猜测吗?

1 个答案:

答案 0 :(得分:1)

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

  

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

无法保证事件只会发生一次。它可能是由监视文件夹的外部进程引起的,例如某种类型的AntiVirus。我会调查一下,因为代码看起来很好。