FileSystemWatcher類可以通過設置IncludeSubdirectories屬性來監視指定目錄及其所有子目錄。當IncludeSubdirectories屬性設置為true時,FileSystemWatcher將監視指定目錄及其所有子目錄中的文件和子目錄的更改。要監視子目錄,只需將IncludeSubdirectories屬性設置為true即可。
以下是一個示例代碼片段,演示如何使用FileSystemWatcher監視指定目錄及其所有子目錄:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Example\Directory";
// 監視所有子目錄中的更改
watcher.IncludeSubdirectories = true;
// 設置要監視的事件類型
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// 添加事件處理程序
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
// 開始監視
watcher.EnableRaisingEvents = true;
// 事件處理程序示例
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} has been changed", e.Name);
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} has been created", e.Name);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} has been deleted", e.Name);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File {0} has been renamed to {1}", e.OldName, e.Name);
}
在上面的示例中,我們創建了一個FileSystemWatcher實例,將其路徑設置為C:\Example\Directory,并將IncludeSubdirectories屬性設置為true,以監視其所有子目錄。然后,我們設置要監視的事件類型,并添加事件處理程序來處理文件更改、創建、刪除和重命名事件。最后,啟用了事件引發以開始監視指定目錄及其所有子目錄的變化。