温馨提示×

FileSystemWatcher如何监控子目录

小樊
111
2024-07-04 00:44:22
栏目: 编程语言

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,以监视其所有子目录。然后,我们设置要监视的事件类型,并添加事件处理程序来处理文件更改、创建、删除和重命名事件。最后,启用了事件引发以开始监视指定目录及其所有子目录的变化。

0