墨香年少 32 发布于 2022年2月8日 using System; using System.IO; namespace MyNamespace { class MyClassCS { static void Main() { using var watcher = new FileSystemWatcher(@"C:\path\to\folder"); watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; watcher.Changed += OnChanged; watcher.Created += OnCreated; watcher.Deleted += OnDeleted; watcher.Renamed += OnRenamed; watcher.Error += OnError; watcher.Filter = "*.txt"; watcher.IncludeSubdirectories = true; watcher.EnableRaisingEvents = true; Console.WriteLine("Press enter to exit."); Console.ReadLine(); } private static void OnChanged(object sender, FileSystemEventArgs e) { if (e.ChangeType != WatcherChangeTypes.Changed) { return; } Console.WriteLine($"Changed: {e.FullPath}"); } private static void OnCreated(object sender, FileSystemEventArgs e) { string value = $"Created: {e.FullPath}"; Console.WriteLine(value); } private static void OnDeleted(object sender, FileSystemEventArgs e) => Console.WriteLine($"Deleted: {e.FullPath}"); private static void OnRenamed(object sender, RenamedEventArgs e) { Console.WriteLine($"Renamed:"); Console.WriteLine($" Old: {e.OldFullPath}"); Console.WriteLine($" New: {e.FullPath}"); } private static void OnError(object sender, ErrorEventArgs e) => PrintException(e.GetException()); private static void PrintException(Exception? ex) { if (ex != null) { Console.WriteLine($"Message: {ex.Message}"); Console.WriteLine("Stacktrace:"); Console.WriteLine(ex.StackTrace); Console.WriteLine(); PrintException(ex.InnerException); } } } } 目之所及,皆是回忆,心之所想,皆是过往 分享这篇帖子 链接帖子 分享到其他站点