C#监控文件夹变化
当需要监控某一文件,FileSystemWatcher类提供了Created, Deleted,Rename等事件。
就拿FileSystemWatcher的Created事件来说,该事件类型是FileSystemEventHandler。
public delgate void FileSystemEventHandler(Object sender, FileSystemEventArgs e)
○ sender表示事件的发起者
○ e表示事件参数
在C盘创建temp文件夹。
客户端。
class Program
{static void Main(string[] args){var watcher = new FileSystemWatcher(@"c:\temp");watcher.EnableRaisingEvents = true; //启用FileSystemWatcherwatcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
Console.ReadKey();}static void OnDeleted(object sender, FileSystemEventArgs e){Console.WriteLine("{0}:{1}", e.ChangeType, e.Name);
}static void OnCreated(object sender, FileSystemEventArgs e){Console.WriteLine("{0}:{1}", e.ChangeType, e.Name);
}static void OnRenamed(object sender, RenamedEventArgs e){Console.WriteLine("{0}:原文件名{1},新文件名{2}", e.ChangeType, e.OldName, e.Name);
}}
当然,可以通过 watcher.Renamed += OnCreated;注册事件。