FileSystemWatcher的Changed事件两次上调 [英] FileSystemWatcher Changed event is raised twice

查看:914
本文介绍了FileSystemWatcher的Changed事件两次上调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我要寻找一个文本文件的应用程序,如果有我使用调用onChanged 事件处理程序来处理该事件对文件所做的任何更改。我现在用的 NotifyFilters.LastWriteTime ,但仍事件被炒鱿鱼的两倍。这里是code。

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event. I am using the NotifyFilters.LastWriteTime but still the event is getting fired twice. Here is the code.

public void Initialize()
{
   FileSystemWatcher _fileWatcher = new FileSystemWatcher();
  _fileWatcher.Path = "C:\\Folder";
  _fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
  _fileWatcher.Filter = "Version.txt";
  _fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
  _fileWatcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
   .......
}

在我的情况下调用onChanged 被调用了两次,当我改变文本文件 version.txt 并保存

In my case the OnChanged is called twice, when I change the text file version.txt and save it.

推荐答案

恐怕这是 FileSystemWatcher的类的著名的bug /功能。这是从类的文档:

I am afraid that this is a well-known bug/feature of the FileSystemWatcher class. This is from the documentation of the class:

您可以在一个单一的创建事件生成由组件处理多个创建的事件某些情况下注意到。例如,如果您使用FileSystemWatcher组件来监控目录中创建新的文件,然后通过使用记事本创建文件进行测试,可以看到,即使只有一个文件被创建产生了两个创建的事件。这是因为,记事本执行在写作过程中多个文件系统操作。记事写入磁盘在创建该文件的内容,然后将文件属性批次。其他应用程序可以以相同的方式执行。由于FileSystemWatcher的监测操作系统的活动,所有的事件,这些应用火将有所回升。

You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up.

现在的文本,该位是有关创建事件,但同样的事情也适用于其他文件事件也是如此。在某些应用中,你可能能够通过使用 NotifyFilter 属性来解决这个问题,但我的经验是说,有时你必须做一些手工重复过滤(黑客),以及

Now this bit of text is about the Created event, but the same thing applies to other file events as well. In some applications you might be able to get around this by using the NotifyFilter property, but my experience is says that sometimes you have to do some manual duplicate filtering (hacks) as well.

前段时间我bookedmarked一个页面有几个 FileSystemWatcher的建议。您可能要检查它。

A while ago I bookedmarked a page with a few FileSystemWatcher tips. You might want to check it out.

这篇关于FileSystemWatcher的Changed事件两次上调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆