基本的 FileWatcher

以下示例创建一个 FileSystemWatcher 来监视运行时指定的目录。该组件设置为监视 LastWriteLastAccess 时间的更改,创建,删除或重命名目录中的文本文件。如果更改,创建或删除文件,则文件的路径将打印到控制台。重命名文件时,旧路径和新路径将打印到控制台。

对于此示例,请使用 System.Diagnostics 和 System.IO 名称空间。

FileSystemWatcher watcher;

private void watch()
{
  // Create a new FileSystemWatcher and set its properties.
  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 handler.
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  // Begin watching.      
  watcher.EnableRaisingEvents = true;
}

// Define the event handler.
private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory or another action.
  Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}