filesystemwatcher

C#中filesystemwatcher怎么使用

小亿
116
2023-07-08 23:06:50
栏目: 编程语言

FileSystemWatcher类是C#中用于监视文件系统更改的类。它可以监视指定目录中的文件和子目录的创建、更改、重命名和删除操作。

以下是使用FileSystemWatcher类的基本步骤:

  1. 创建一个新的FileSystemWatcher对象,并指定要监视的目录路径。
FileSystemWatcher watcher = new FileSystemWatcher("目录路径");
  1. 可选:设置FileSystemWatcher对象的属性,以指定要监视的文件类型或其他选项。
watcher.Filter = "*.txt"; // 只监视文本文件
watcher.IncludeSubdirectories = true; // 包括子目录中的文件
  1. 注册事件处理程序,以响应文件系统更改事件。
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
  1. 实现事件处理程序。
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)
{
// 处理文件重命名事件
}
  1. 启动FileSystemWatcher对象的监视。
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"键退出程序。

0
看了该问题的人还看了