文件更改时通知?


111

在光盘上修改文件时,是否可以通过某种机制(在C#中)通知我?


1
有关FileSystemWatcher类及其引发的事件的更多信息,请参见此答案
克里斯·

Answers:



204

您可以使用FileSystemWatcher该类。

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);
}

11
感谢您的好例子。我还将指出,如果您正在寻找一种阻止(同步)方式来监视更改的方法,则可以在FileSystemWatcher上使用WaitForChanged方法。
Mark Meuer 2013年

22
谢谢这个例子。MSDN在这里几乎相同。另外,有些人可能希望观察整个目录树-使用它watcher.IncludeSubdirectories = true;来实现。
奥利弗·

1
OnChange在没有实际更改的情况下触发(例如:在ctrl+s没有任何实际更改的情况下进行击中),是否有任何方法可以检测到虚假更改?
Mehdi Dehghani

1
@MehdiDehghani:我不知道,唯一的方法似乎是实际上保留文件的快照并将其按字节与当前(可能已更改)的版本进行比较。该FileSystemWatcher只能够检测在文件系统级事件(即如果OS触发事件)。在您的情况下,Ctrl + S会触发此类事件(尽管是否发生取决于实际的应用程序)。
德克·沃尔玛

FileSystemWatcher是跨平台的吗?
Vinigas

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.