C#中的FileSystemWatcher類用于監(jiān)視文件系統(tǒng)中的更改,例如創(chuàng)建、修改、刪除或重命名文件或目錄。下面是使用FileSystemWatcher類的基本步驟:
using System.IO;
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "路徑";
watcher.Filter = "文件過濾器";
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
private static void OnCreated(object source, FileSystemEventArgs e)
{
// 當文件或目錄被創(chuàng)建時執(zhí)行的操作
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
// 當文件或目錄被修改時執(zhí)行的操作
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
// 當文件或目錄被刪除時執(zhí)行的操作
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// 當文件或目錄被重命名時執(zhí)行的操作
}
watcher.EnableRaisingEvents = true;
這樣就可以使用FileSystemWatcher類來監(jiān)視文件系統(tǒng)中的更改了。在每個事件處理程序中,您可以執(zhí)行自定義的操作,例如記錄更改、處理文件、發(fā)送通知等。