C# 监控文件夹文件变化:使用 FileSystemWatcher 类
在 C# 中,可以使用FileSystemWatcher 类来监控文件夹中的文件变化。下面是一个简单的示例代码:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// 创建一个新的 FileSystemWatcher 对象
FileSystemWatcher watcher = new FileSystemWatcher();
// 设置要监控的文件夹路径
watcher.Path = 'C:\Path\To\Folder';
// 只监控文件的变化,不包括子文件夹
watcher.IncludeSubdirectories = false;
// 设置要监控的文件类型
watcher.Filter = '*.*';
// 注册事件处理程序
watcher.Created += OnFileChanged;
watcher.Deleted += OnFileChanged;
watcher.Changed += OnFileChanged;
watcher.Renamed += OnFileRenamed;
// 开始监控
watcher.EnableRaisingEvents = true;
// 等待退出
Console.WriteLine('Press 'q' to quit the program.');
while (Console.Read() != 'q') ;
}
// 文件创建、删除、修改事件处理程序
static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($'File {e.ChangeType}: {e.FullPath}');
}
// 文件重命名事件处理程序
static void OnFileRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($'File renamed: {e.OldFullPath} => {e.FullPath}');
}
}
在上面的代码中,我们创建了一个FileSystemWatcher 对象,并设置了要监控的文件夹路径、要监控的文件类型等属性。然后,我们注册了几个事件处理程序,分别处理文件的创建、删除、修改和重命名事件。最后,我们调用EnableRaisingEvents 方法开始监控文件夹中的文件变化。
注意,FileSystemWatcher 类可能会产生大量的事件,因此在实际使用中需要根据需求进行适当的处理,例如使用Filter 属性过滤文件类型,或者使用IncludeSubdirectories 属性监控子文件夹中的文件变化。
原文地址: https://www.cveoy.top/t/topic/bsj5 著作权归作者所有。请勿转载和采集!