主要是使用系统自带的System.IO.FileSystemWatcher这个类,废话不多说,直接上代码:
/// <summary>/// 文件监听/// </summary>public class FileFolderMonitor{private FileSystemWatcher fileSystemWatcher;/// <summary>/// 开启监听/// </summary>/// <param name="directoryPath">文件目录</param>public void StartMonitoring(string directoryPath){fileSystemWatcher = new FileSystemWatcher();// 监听的目录路径fileSystemWatcher.Path = directoryPath;// 监听的事件类型(例如:修改、创建、删除)fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;// 添加事件处理eventfileSystemWatcher.Changed += OnChanged;fileSystemWatcher.Created += OnChanged;//_fileWatcher.Deleted += OnChanged;//_fileWatcher.Renamed += OnRenamed;// 开启事件监听fileSystemWatcher.EnableRaisingEvents = true;LogHelper.Info($"已开始监听文件夹: {directoryPath}");}private void OnChanged(object source, FileSystemEventArgs e){LogHelper.Info($"文件或文件夹发生变化: {e.FullPath},事件类型: {e.ChangeType}");Task task = new Task(() => {//todo...});task.Start();}private void OnRenamed(object source, RenamedEventArgs e){LogHelper.Info($"相关资源被重命名: 重命名之前的绝对路径 {e.OldFullPath} 重命名之后的绝对路径 {e.FullPath}");}public void StopMonitoring(){if (fileSystemWatcher != null){// 停止引发事件fileSystemWatcher.EnableRaisingEvents = false;// 清理资源fileSystemWatcher.Dispose();fileSystemWatcher = null;LogHelper.Info("已停止监听文件夹");}}}