首页 新闻 会员 周边

FileSystemWatcher的Changed事件会触发两次

0
[待解决问题]
private void FileSystemWatcher(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher();
try
{
watcher.Path = path;
}
catch (ArgumentException e)
{
Record("错误:" + e.Message);
return;
}
watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.Size;
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(this.FileChange_EventHandle);
watcher.Deleted += new FileSystemEventHandler(this.FileChange_EventHandle);
watcher.Changed += new FileSystemEventHandler(this.FileChange_EventHandle);
watcher.Renamed += new RenamedEventHandler(this.FileChange_Renamed);

}
DateTime lastRead = DateTime.MinValue;
private void FileChange_EventHandle(object source, FileSystemEventArgs e)
{
//Record("测试FileChange_EventHandle");
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastRead != lastWriteTime)
{
Record($"测试FileChange_EventHandle_{e.ChangeType.ToString()}\r\n{lastRead.ToString()}\r\n{lastWriteTime.ToString()}\r\n{e.FullPath}\r\n{DateTime.Compare(lastRead, lastWriteTime)}");
lastRead = lastWriteTime;
}

}

 

 

 尝试以时间来进行判断,但是诡异的是时间一样还是会进入判断

请问下有什么方法能让changed事件只执行一次?

bgh的主页 bgh | 初学一级 | 园豆:45
提问于:2022-02-27 01:32
< >
分享
所有回答(3)
0

我用的是记事本测试,并没有复现你的问题。该触发一次还是一次……

寂静的羽夏 | 园豆:1781 (小虾三级) | 2022-02-27 09:25

。。。不知道什么情况了

支持(0) 反对(0) bgh | 园豆:45 (初学一级) | 2022-02-27 20:17
0
watcher.Created += new FileSystemEventHandler(this.FileChange_EventHandle);
watcher.Deleted += new FileSystemEventHandler(this.FileChange_EventHandle);
watcher.Changed += new FileSystemEventHandler(this.FileChange_EventHandle);

有没有可能是Created事件也被触发导致的

可以在事件处理程序里把文件内容打印出来进行调试

Laggage | 园豆:878 (小虾三级) | 2022-02-27 20:14

我用了e.ChangeType.ToString()来看触发的事件都是change,也把created事件取消过,还是会触发两次

支持(0) 反对(0) bgh | 园豆:45 (初学一级) | 2022-02-27 20:17

@bgh: 在事件处理程序里把文件内容打印出来进行调试,看看是什么东西变了,或者把中文输入法关了试试?

支持(0) 反对(0) Laggage | 园豆:878 (小虾三级) | 2022-02-27 20:20

@Laggage: 内容没变,一模一样。。。关闭中文输入法也是触发两次。。。

支持(0) 反对(0) bgh | 园豆:45 (初学一级) | 2022-02-27 20:31

@bgh: 我看到了这一行

watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.CreationTime | NotifyFilters.Size;

NotifyFilters.Size这个应该也有影响的吧

支持(0) 反对(0) Laggage | 园豆:878 (小虾三级) | 2022-02-27 20:34

@bgh: 把watcher.NotifyFilter这一行注释掉用默认值

支持(0) 反对(0) Laggage | 园豆:878 (小虾三级) | 2022-02-27 20:38

@Laggage: 注释size的话我该了内容也不触发change了,使用默认的话还是触发了两次。。。

支持(0) 反对(0) bgh | 园豆:45 (初学一级) | 2022-02-27 20:40
0

你自己设置断点到FileChange_EventHandle事件处理函数当中,运行一下看看就知道了。

xsz1234 | 园豆:39 (初学一级) | 2022-07-20 17:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册