FileSystemWatcher类是C#中用于监视文件系统更改的类。它可以监视指定目录中的文件和子目录的创建、更改、重命名和删除操作。
以下是使用FileSystemWatcher类的基本步骤:
FileSystemWatcher watcher = new FileSystemWatcher("目录路径");
watcher.Filter = "*.txt"; // 只监视文本文件
watcher.IncludeSubdirectories = true; // 包括子目录中的文件
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
private static void OnCreated(object source, FileSystemEventArgs e)
{
// 处理文件创建事件
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
// 处理文件更改事件
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
// 处理文件删除事件
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// 处理文件重命名事件
}
watcher.EnableRaisingEvents = true;
完整示例代码:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher("目录路径");
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press 'q' to quit.");
while (Console.Read() != 'q') ;
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("Created: " + e.FullPath);
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("Changed: " + e.FullPath);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("Deleted: " + e.FullPath);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("Renamed: " + e.OldFullPath + " to " + e.FullPath);
}
}
此示例会监视指定目录中的所有文本文件的创建、更改、删除和重命名事件,并在控制台输出相应的信息。按下"q"键退出程序。