监视文件夹的文件变更
监视文件夹的文件变更
using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Watch(); } static DateTime now = DateTime.Now; static string fileName = string.Empty; private static void Watch() { FileSystemWatcher myWatcher = new FileSystemWatcher("E:\\drivers"); myWatcher.Filter = "*.*"; myWatcher.EnableRaisingEvents = true; myWatcher.Changed += new FileSystemEventHandler(myWatcher_Changed); myWatcher.Created += new FileSystemEventHandler(myWatcher_Created); myWatcher.Deleted += new FileSystemEventHandler(myWatcher_Deleted); myWatcher.Renamed += new RenamedEventHandler(myWatcher_Renamed); Console.Read(); } static void myWatcher_Renamed(object sender, RenamedEventArgs e) { if ((DateTime.Now - now).TotalMilliseconds > 100 || fileName != e.Name) { Console.WriteLine(string.Format("{0} --重命名-- {1}", e.OldName, e.Name)); fileName = e.Name; now = DateTime.Now; } } static void myWatcher_Deleted(object sender, FileSystemEventArgs e) { if ((DateTime.Now - now).TotalMilliseconds > 100 || fileName != e.Name) { Console.WriteLine("删除"); fileName = e.Name; now = DateTime.Now; } } static void myWatcher_Created(object sender, FileSystemEventArgs e) { if ((DateTime.Now - now).TotalMilliseconds > 100 || fileName != e.Name) { Console.WriteLine("创建"); fileName = e.Name; now = DateTime.Now; } } static void myWatcher_Changed(object sender, FileSystemEventArgs e) { if ((DateTime.Now - now).TotalMilliseconds > 100 || fileName != e.Name) { Console.WriteLine("内容改变"); fileName = e.Name; now = DateTime.Now; } } } }