【问题标题】:Notification when a file changes?文件更改时通知?
【发布时间】:2009-04-06 14:30:59
【问题描述】:

当磁盘上的文件被修改时,是否有某种机制可以通知我(在 C# 中)?

【问题讨论】:

  • 有关 FileSystemWatcher 类及其引发的事件的更多信息,请参阅answer。

标签: c# file filesystemwatcher


【解决方案1】:

您可以使用@987654321@ 类。

public void CreateFileWatcher(string path)
{
    // Create a new FileSystemWatcher and set its properties.
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = path;
    /* Watch for changes in LastAccess and LastWrite times, and 
       the renaming of files or directories. */
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    // Only watch text files.
    watcher.Filter = "*.txt";

    // Add event handlers.
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnRenamed);

    // Begin watching.
    watcher.EnableRaisingEvents = true;
}

// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
   Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

private static void OnRenamed(object source, RenamedEventArgs e)
{
    // Specify what is done when a file is renamed.
    Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}

【讨论】:

  • 谢谢你的好例子。我还要指出,如果您正在寻找一种阻塞(同步)方式来监视更改,您可以在 FileSystemWatcher 上使用 WaitForChanged 方法。
  • 感谢这个例子。 MSDN 的here 几乎相同。此外,有些人可能想要查看整个目录树 - 使用 watcher.IncludeSubdirectories = true; 来实现。
  • OnChange 在没有实际更改的情况下触发(例如:在没有任何实际更改的情况下点击ctrl+s),有没有办法检测到虚假更改?
  • @MehdiDehghani:据我所知,唯一的方法似乎是实际保留文件的快照并将该文件按字节与当前(可能已更改)版本进行比较。 FileSystemWatcher 只能检测文件系统级别的事件(即,如果操作系统触发事件)。在你的情况下 Ctrl+S 触发这样一个事件(是否发生取决于实际的应用程序)。
  • FileSystemWatcher 是跨平台的吗?
【解决方案2】:

【讨论】:

    【解决方案3】:

    使用FileSystemWatcher。您只能过滤修改事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-02
      • 2018-10-05
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多