本帖最后由 张满满 于 2023-10-18 15:14 编辑
- using System;
- using System.IO;
- class Program
- {
- static void Main(string[] args)
- {
- // 设置要监测的文件夹路径
- string folderPath = "C:\\YourFolderPath";
- // 创建一个新的FileSystemWatcher实例
- FileSystemWatcher watcher = new FileSystemWatcher(folderPath);
- // 设置要监测的文件类型(可选)
- watcher.Filter = "*.*";
- // 监听文件或文件夹的创建、更改、删除和重命名事件
- watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
- // 添加事件处理方法
- watcher.Created += OnFileChanged;
- watcher.Deleted += OnFileChanged;
- watcher.Changed += OnFileChanged;
- watcher.Renamed += OnFileRenamed;
- // 启动监测
- watcher.EnableRaisingEvents = true;
- // 持续运行,直到按下任意键退出
- Console.WriteLine("正在监测文件夹中的文件变化...");
- Console.ReadKey();
- }
- // 文件创建、更改、删除事件处理方法
- private static void OnFileChanged(object sender, FileSystemEventArgs e)
- {
- Console.WriteLine($"{e.ChangeType}: {e.FullPath}");
- }
- // 文件重命名事件处理方法
- private static void OnFileRenamed(object sender, RenamedEventArgs e)
- {
- Console.WriteLine($"重命名: {e.OldFullPath} -> {e.FullPath}");
- }
- }
复制代码
|