如何在不触发无限循环的情况下编写 FileSystemWatcher

How to write FileSystemWatcher without triggering an infinite loop

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

我的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() 写入修改后的文件时,它会触发 FileSystemWatcher 的 Change 事件,因为该操作被再次注册为写入。

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

如何用备份副本替换修改后的文件,而不触发 FileSystemWatcher 写入的另一个事件?

除了您可以使用 OS 文件安全性 f.e 以 better/different 方式解决问题之外,您还有一些选择:

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