1. 程式人生 > 其它 >.net 監聽本地目錄

.net 監聽本地目錄

捕獲事件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); }