VB.NET FileSystemWatcher多个更改事件

Joh*_*lak 11 .net vb.net filesystemwatcher

我有以下代码:


Imports System.IO

Public Class Blah
    Public Sub New()
        InitializeComponent()

        Dim watcher As New FileSystemWatcher("C:\")
        watcher.EnableRaisingEvents = True

        AddHandler watcher.Changed, AddressOf watcher_Changed
    End Sub

    Private Sub watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)
        MsgBox(e.FullPath)
    End Sub
End Class

当我运行它并将更改保存到我的C驱动器上的文件时,代码工作得很好,除了它执行watcher_Changed()方法四次.知道为什么吗?每次changeType为"4".

谢谢.

Joh*_*lak 16

从VS.NET文档的"疑难解答FileSystemWatcher组件"部分...

为单个操作生成的多个创建事件

在某些情况下,您可能会注意到单个创建事件会生成由组件处理的多个Created事件.例如,如果使用FileSystemWatcher组件来监视目录中新文件的创建,然后使用记事本创建文件进行测试,即使只创建了一个文件,也可能会看到生成两个Created事件.这是因为Notepad在写入过程中执行多个文件系统操作.记事本批量写入磁盘,创建文件的内容,然后创建文件属性.其他应用程序可以以相同的方式执行.由于FileSystemWatcher监视操作系统活动,因此将拾取这些应用程序触发的所有事件.

注意:记事本也可能导致其他有趣的事件生成.例如,如果使用ChangeEventFilter指定只想查看属性更改,然后使用记事本写入正在查看的目录中的文件,则会引发事件.这是因为记事本在此操作期间更新了文件的Archived属性.


Fre*_*els 14

不久前,我遇到了同样的问题.

经过对网络的一些搜索后,似乎我不是唯一一个有这个问题的人.:)所以,也许这是FileSystemWatcher中的一个缺陷......

我通过跟踪最后一次提出事件处理程序来解决它.如果它在xxx毫秒之前被提升,我将从我的事件处理程序返回.如果有人知道更优雅的修复; 请告诉我.:)

这就是我如何解决它:

if( e.ChangeType == WatcherChangeTypes.Changed )
{

    // There is a nasty bug in the FileSystemWatch which causes the 
    // events of the FileSystemWatcher to be called twice.
    // There are a lot of resources about this to be found on the Internet,
    // but there are no real solutions.
    // Therefore, this workaround is necessary: 
    // If the last time that the event has been raised is only a few msec away, 
    // we ignore it.
    if( DateTime.Now.Subtract (_lastTimeFileWatcherEventRaised).TotalMilliseconds < 500 )
    {
        return;
    }


    _lastTimeFileWatcherEventRaised = DateTime.Now;


    .. handle event
Run Code Online (Sandbox Code Playgroud)