如何在不触发无限循环的情况下编写文件系统观察器



如何将 C# 中的文件写入 FileSystemWatcher 监视的文件夹路径?

我的文件系统观察器设置如下:

public FileSystemWatcher CreateAndExecute(string path)
{
Console.WriteLine("Watching " + path);
//Create new watcher
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
fileSystemWatcher.Path = path;
fileSystemWatcher.IncludeSubdirectories = false;
fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | 
NotifyFilters.FileName | NotifyFilters.DirectoryName;
fileSystemWatcher.Filter = "*.txt";
fileSystemWatcher.Changed += new FileSystemEventHandler(OnChange);
fileSystemWatcher.InternalBufferSize = 32768;
//Execute
fileSystemWatcher.EnableRaisingEvents = true;
}
private void OnChange(object source, FileSystemEventArgs e)
{
//Replace modified file with original copy
}

我想在文件发生未经授权的写入(程序外(时用数据库中的备份副本替换修改后文件的内容。

但是,当我使用 File.WriteAllText(( 写入修改后的文件时,它会触发文件系统观察器的 Change 事件,因为该操作再次注册为写入。

这会导致程序在覆盖它刚刚写入的文件的无限循环中运行。

如何将修改后的文件替换为备份副本,而不会触发文件系统观察器写入的另一个事件?

除了您可能可以通过使用操作系统文件安全性以更好/不同的方式解决问题之外,您还有一些选择:

  • 暂时禁用观察程序,在这种情况下,您可以在暴力攻击的情况下丢失事件,这可能不是您想要的。
  • 保留一个包含您重写的文件的列表,并忽略列表中文件的一项更改,然后将其从列表中删除 - 如果恶意程序知道这一点,>也可能被滥用
  • 存储文件内容的 SHA1 或 SHA256(或其他哈希(,并且仅在哈希不同时才替换文件 ->可能是解决此问题的最佳方法

相关内容