基本的 FileWatcher
以下示例建立一個 FileSystemWatcher
來監視執行時指定的目錄。該元件設定為監視 LastWrite 和 LastAccess 時間的更改,建立,刪除或重新命名目錄中的文字檔案。如果更改,建立或刪除檔案,則檔案的路徑將列印到控制檯。重新命名檔案時,舊路徑和新路徑將列印到控制檯。
對於此示例,請使用 System.Diagnostics 和 System.IO 名稱空間。
FileSystemWatcher watcher;
private void watch()
{
// Create a new FileSystemWatcher and set its properties.
watcher = new FileSystemWatcher();
watcher.Path = path;
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt*";
// Add event handler.
watcher.Changed += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handler.
private void OnChanged(object source, FileSystemEventArgs e)
{
//Copies file to another directory or another action.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}