c#的文件监视器监视多类文件
时间: 2025-01-20 09:17:55 浏览: 30
在C#中,文件监视器可以通过`FileSystemWatcher`类来实现。`FileSystemWatcher`类提供了一种机制,用于监视文件系统中的更改,如文件的创建、修改、删除和重命名。通过设置适当的过滤器,可以监视特定类型的文件。
以下是一个示例代码,展示了如何使用`FileSystemWatcher`类来监视多种类型的文件:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
// 监视的目录
string directoryToWatch = @"C:\Your\Directory\Path";
// 创建FileSystemWatcher实例
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
// 设置监视的路径
watcher.Path = directoryToWatch;
// 设置过滤器,监视多种类型的文件
watcher.Filter = "*.txt|*.doc|*.jpg";
// 监视所有事件
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite;
// 订阅事件
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
// 开始监视
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
}
// 定义事件处理程序
private static void OnChanged(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
private static void OnCreated(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
private static void OnDeleted(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
private static void OnRenamed(object sender, RenamedEventArgs e) =>
Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
```
在这个示例中,`FileSystemWatcher`被配置为监视特定目录中的`.txt`、`.doc`和`.jpg`文件。通过设置`Filter`属性为`"*.txt|*.doc|*.jpg"`,可以实现对多种文件类型的监视。
阅读全文
相关推荐



















