C#中FileSystemWatcher类实现监控文件夹

  using System;

  using System.IO;

  class Program

  {

  static void Main()

  {

  // 创建FileSystemWatcher实例

  FileSystemWatcher watcher = new FileSystemWatcher();

  // 设置要监视的目录

  watcher.Path = @"C:YourFolderToWatch";

  // 过滤条件,例如只监控.txt文件

  watcher.Filter = "*.txt";

  // 通知过滤器,设置需要监控的事件类型

  watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;

  // 注册事件处理器

  watcher.Created += OnFileCreated;

  watcher.Deleted += OnFileDeleted;

  watcher.Changed += OnFileChanged;

  watcher.Renamed += OnFileRenamed;

  // 开始监控

  watcher.EnableRaisingEvents = true;

  // 保持控制台开启,以便接收事件

  Console.WriteLine("Press 'Enter' to quit the sample.");

  Console.ReadLine();

  // 停止监控

  watcher.EnableRaisingEvents = false;

  }

  // 当文件被创建时触发

  private static void OnFileCreated(object source, FileSystemEventArgs e)

  {

  Console.WriteLine($"File: {e.FullPath} has been created.");

  }

  // 当文件被删除时触发

  private static void OnFileDeleted(object source, FileSystemEventArgs e)

  {

  Console.WriteLine($"File: {e.FullPath} has been deleted.");

  }

  // 当文件被修改时触发

  private static void OnFileChanged(object source, FileSystemEventArgs e)

  {

  Console.WriteLine($"File: {e.FullPath} has been changed.");

  }

  // 当文件被重命名时触发

  private static void OnFileRenamed(object source, RenamedEventArgs e)

  {

  Console.WriteLine($"File: {e.OldFullPath} has been renamed to {e.FullPath}.");

  }

  }