using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApplication1 { internal class Program { private static void Main(string[] args) { var watcher2 = new FileWatch(@"E: 01.BLK"); watcher2.Start(); Console.Read(); } } public class FileWatch { private readonly FileSystemWatcher __fileWatcher; private readonly HashSet<string> __hstbWatcher; public FileWatch(string filePath) { __hstbWatcher = new HashSet<string>(); if (__fileWatcher == null) { FileInfo file = new FileInfo(filePath); __fileWatcher = new FileSystemWatcher(file.DirectoryName) { Filter = file.Name, NotifyFilter = NotifyFilters.LastWrite }; __fileWatcher.Changed += _watcher_Changed; } } public void Start() { __fileWatcher.EnableRaisingEvents = true; } public void Stop() { __fileWatcher.EnableRaisingEvents = false; } private void _watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("执行一次..."); if (__hstbWatcher.Any(q => q.Equals(e.FullPath, StringComparison.CurrentCultureIgnoreCase))) { lock (__hstbWatcher) { __hstbWatcher.Remove(e.FullPath); return; } } lock (__hstbWatcher) { __hstbWatcher.Add(e.FullPath); } Console.WriteLine(e.FullPath + " " + e.ChangeType); } } }