c# - FileSystemWatcher:忽略自己进程所做的更改

标签 c# .net windows filesystemwatcher

我想问一下是否有可能忽略 由自己的进程 FileSystemWatcher 生成的文件系统更改事件 正在运行。 例如,我自己的进程在监视目录中创建了一个文件,并且 FileSystemWatcher 应该认识到它是由进程创建的,或者 不要从一开始就引发事件。

最佳答案

您可以使用应用程序操作的文件列表:

static private readonly List<string> WatcherFilesToIgnore = new List<string>();
try
{
  WatcherFilesToIgnore.Add(filePath1);
  WatcherFilesToIgnore.Add(filePath2);
  // some file operation
}
finally
{
  WatcherFilesToIgnore.Remove(filePath1);
  WatcherFilesToIgnore.Remove(filePath2);
}

因此在您在开头编写的观察者事件处理程序中:

if ( WatcherFilesToIgnore.Contains(e.FullPath) ) return;
// watcher process

因此,当您的应用程序对某些文件进行操作时,watcher 将不执行任何操作以忽略指定的文件。

如果您使用多线程,请考虑使用一些同步。


正如@CodeCaster 所提到的,应用程序和引发的 windows shell 事件之间可能存在延迟。

一个简单的事情就是添加一个 Sleep(2000)例如,但它可能是危险的。

因此我们可以使用 Dictionary<string, bool>指示进程已终止并让观察者自行清理列表:

WatcherFilesToIgnore.Add(filePath1, false);
// file operation
WatcherFilesToIgnore[filePath1] = true;
if ( WatcherFilesToIgnore.Contains(e.FullPath) ) 
{
  if ( WatcherFilesToIgnore[e.FullPath] )
    WatcherFilesToIgnore.Remove(e.FullPath);
  return;
}
// watcher process

这仅在引发真正的观察者事件时有效,否则文件将保留在列表中。

所以我们需要确保在什么都不做的情况下我们删除文件:

WatcherFilesToIgnore.Add(filePath1, false);

if ( ProcessFile(filePath1) )
  WatcherFilesToIgnore[filePath1] = true;
else
  WatcherFilesToIgnore.Remove(e.FullPath);

ProcessFile方法(我在解释中考虑了这一点)执行所需的操作并在某些更改成功时返回 true,否则返回 false(未执行任何操作、引发异常、进程中止...)。

关于c# - FileSystemWatcher:忽略自己进程所做的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64005005/

相关文章:

c# - 为什么 C# 是一种快速应用程序开发 (RAD) 语言?

C# XSLT 快速转换大型 XML 文件

c# - 等待线程池上的所有任务完成

.Net Profiling API 方法

C# 和.NET : stackalloc

windows - 如何删除警告 LNK4099 : PDB 'lib.pdb' was not found

c# - 为什么 Application.LocalUserAppDataPath 抛出 InvalidDeploymentException "Application identity is not set."

c# - 神圣的倒影

windows - 如何在当前 Puppet session 中设置 Windows 环境路径?

windows - ColdFusion 9 集群与 IIS7.5