捕获事件FileSystemWatcher
例子:
/// <summary> /// 监听目录 /// </summary> /// <param name="path">目录</param> /// <param name="filter">过滤器(文件类型)</param> /// <param name="includeSubDirs">是否递归子目录</param> static void Watch(string path, string filter, bool includeSubDirs) { using (var watcher=new FileSystemWatcher(path,filter)) { watcher.Created += Watcher_Changed; watcher.Deleted += Watcher_Changed; watcher.Changed += Watcher_Changed; watcher.Renamed += Watcher_Renamed; watcher.Error += Watcher_Error; watcher.IncludeSubdirectories = includeSubDirs; watcher.EnableRaisingEvents = true; Console.WriteLine("Listening for - pree<Enter> to end"); Console.ReadLine(); } } private static void Watcher_Renamed(object sender, RenamedEventArgs e) { Console.WriteLine($"Renamed:{e.OldFullPath} => {e.FullPath}"); } private static void Watcher_Error(object sender, ErrorEventArgs e) { Console.WriteLine($"Error:+{e.GetException().Message}"); } private static void Watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine($"File {e.FullPath} has been {e.ChangeType}"); } static void Main(string[] args) { Watch(@"C:\Users\Administrator\Desktop\IO", "*.*", true); }