C#利用FileSystemWatcher实时监控文件的增加,修改,重命名和删除
在C#中,可以使用FileSystemWatcher类实现对文件夹进行监视,实现对文件夹中文件的增加
、修改
、重命名
和删除
等操作的即时监控。
FileSystemWatcher基本用法
- 创建FileSystemWatcher对象
FileSystemWatcher watcher = new FileSystemWatcher();
- 设置FileSystemWatcher对象的需要监控的文件夹路径
watcher.Path = @"C:\SomePath";
- 设置需要监控的文件类型
watcher.Filter = "*.*";
- 启动监视
watcher.EnableRaisingEvents = true;
- 为FileSystemWatcher注册监控事件
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
- 定义监视事件的处理方法
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File {e.FullPath} has been {e.ChangeType}");
}
private static void OnRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"File {e.OldFullPath} has been renamed to {e.FullPath}");
}
private static void OnDeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File {e.FullPath} has been deleted");
}
示例一:监视文件夹中的文件即时增加事件
// 创建FileSystemWatcher对象
FileSystemWatcher watcher = new FileSystemWatcher();
// 设置FileSystemWatcher对象的需要监控的文件夹路径
watcher.Path = @"C:\SomePath";
// 设置需要监控的文件类型
watcher.Filter = "*.*";
// 启动监视
watcher.EnableRaisingEvents = true;
// 为FileSystemWatcher注册监控事件
watcher.Created += new FileSystemEventHandler(OnFileAdded);
// 定义监视事件的处理方法
private static void OnFileAdded(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File {e.FullPath} has been added to the folder");
}
示例二:监视文件夹中的文件即时修改事件
// 创建FileSystemWatcher对象
FileSystemWatcher watcher = new FileSystemWatcher();
// 设置FileSystemWatcher对象的需要监控的文件夹路径
watcher.Path = @"C:\SomePath";
// 设置需要监控的文件类型
watcher.Filter = "*.*";
// 启动监视
watcher.EnableRaisingEvents = true;
// 为FileSystemWatcher注册监控事件
watcher.Changed += new FileSystemEventHandler(OnFileChanged);
// 定义监视事件的处理方法
private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File {e.FullPath} has been modified");
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#利用FileSystemWatcher实时监控文件的增加,修改,重命名和删除 - Python技术站