1. 程式人生 > 其它 >FileSystemWatcher 監控檔案變化

FileSystemWatcher 監控檔案變化

以程式設計方式觀察檔案
FileSystemWatcher類
通過System.IO.NotifyFilters 列舉來決定需要FileSystemWatcher型別監控檔案的行為
public enum NotifyFilters
{
Attributes,
CreationTime,
DirectoryName,
FileName,
LastAccess,
LastWrite,
Security,
Size
}

使用FileSystemWatcher型別的第一步是設定 Path 屬性,以制定需要監控的檔案所在的資料夾的名字,還有就是定義需要監控檔案的副檔名的Filter屬性
第二步使用FileSystemEventHandler委託關聯的事件來實現Changed、Created和Deleted事件的處理方法。
這個委託符合下列模式:
void MyNotificationHandler(object source,FileSystemEventArgs e);
同樣Renamed事件也可以通過RenamedEventHandler
void MyRenamedHandler(object source,RenamedEventArgs e);
(1) FileSystemWatcher watcher=new FileSystemWatcher();
watcher.Path=@"C:\myfolder"; //指定監控路徑
(2) watcher.NotifyFilter=NotifyFilters.LastAccess|NotfiyFilters.LastWrite|NotifyFilters.FileName|NotifyFilters.DirectoryName; //設定需要留意的事情
(3) watcher.Filter="*.txt"; //只觀察文字檔案
(4) watcher.Changed+=new FileSystemEventHandler(OnChanged); //增加事件處理程式
watcher.Created+=new FileSystemEventHandler(OnChanged);
watcher.Deleted+=new FileSystemEventHandler(OnChanged);
watcher.Renamed+=new RenamedEventHandler(OnRenamed);
(5) watcher.EnableRaisingEvents=true; //開始觀察目錄