public static void Main(string[] args) { //建立一個新的FileSystemWatcher並設置其屬性 FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = "F:\\"; /*監視LastAcceSS和LastWrite時間的更改以及文件或目錄的重命名*/ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; //只監視文本文件 watcher.Filter = "*.txt"; //添加事件句柄 //當由FileSystemWatcher所指定的路徑中的文件或目錄的 //大小、系統屬性、最後寫時間、最後訪問時間或安全權限 //發生更改時,更改事件就會發生 watcher.Changed += new FileSystemEventHandler(OnChanged); //由FileSystemWatcher所指定的路徑中文件或目錄被建立時,建立事件就會發生 //watcher.Created += new FileSystemEventHandler(OnChanged); //當由FileSystemWatcher所指定的路徑中文件或目錄被刪除時,刪除事件就會發生 //watcher.Deleted += new FileSystemEventHandler(OnChanged); //當由FileSystemWatcher所指定的路徑中文件或目錄被重命名時,重命名事件就會發生 //watcher.Renamed += new RenamedEventHandler(OnRenamed); //開始監視 watcher.EnableRaisingEvents = true; //等待用戶退出程序 //Console.WriteLine(DateTime.Now+",Press\'q\' to quit the sample."); while (Console.Read() != 'q') ; } //定義事件處理程序 public static void OnChanged(object sender, FileSystemEventArgs e) { var watcher = sender as FileSystemWatcher; watcher.EnableRaisingEvents = false; //指定當文件被更改、建立或刪除時要作的事 Console.WriteLine(DateTime.Now+",file:" + e.FullPath + "" + e.ChangeType); watcher.EnableRaisingEvents = true; }
解決方法:安全
只須要在開始處理時先作:watcher.EnableRaisingEvents = false;ui
結束後再作:watcher.EnableRaisingEvents = true;spa