利用 C# 中的 FileSystemWatcher 制作一个文件夹监控小工具
利用 C# 中的 FileSystemWatcher 制作一个文件夹监控小工具
独立观察员 2020 年 12 月 26 日
前一段看到微信公众号 “码农读书” 上发了一篇文章《 如何使用 C# 中的 FileSystemWatcher 》(翻译自: https://www. infoworld.com/article/3 185447/how-to-work-with-filesystemwatcher-in-c.html ),其中简述了使用FileSystemWatcher进行文件系统变更监测的方法,本人受此启发,决定制作一个文件夹内变动监控的小工具,当作练手和自用。目前该工具已制作完成,故发文分享给大家。

功能比较简单,运行程序后,点击 “选择文件夹” 按钮选择想要监控的文件夹,然后点击 “开始监控文件变动” 即可。可以检测文件夹 / 文件 的创建、删除、修改、重命名,然后在信息窗中输出相关信息。如果取消勾选 “是否显示完全路径”,则输出的信息中将不包含选择的 “文件夹路径” 部分,也就是显示的是相对路径。如果取消勾选 “是否监控子文件夹”,则程序将不监控子文件夹内的变动情况。
保存配置按钮可进行保存如下信息,下次打开程序会恢复保存的状态:

关键代码如下(文末会给出代码仓库地址):
#region 文件夹监控
private FileSystemWatcher _FileSystemWatcher = new FileSystemWatcher();
// 参考:https://www.infoworld.com/article/3185447/how-to-work-with-filesystemwatcher-in-c.html
/// <summary>/// 开始监控目录/// </summary>/// <param name="path"> 目录路径 </param>/// <param name="isIncludeSubDir"> 是否包括子目录 </param>private async void MonitorDirectory(string path, bool isIncludeSubDir = true){ _FileSystemWatcher.EnableRaisingEvents = false; _FileSystemWatcher = new FileSystemWatcher(); _FileSystemWatcher.Path = path; _FileSystemWatcher.IncludeSubdirectories = isIncludeSubDir;
_FileSystemWatcher.Created += FileSystemWatcher_Created; _FileSystemWatcher.Renamed += FileSystemWatcher_Renamed; _FileSystemWatcher.Deleted += FileSystemWatcher_Deleted; _FileSystemWatcher.Changed += FileSystemWatcher_Changed;
// 开始监控 _FileSystemWatcher.EnableRaisingEvents = true;
await ConfirmBoxHelper.ShowMessage(DialogVm, $" 已开启监控:[{Configs.FolderPath}]");}
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e){ Console.WriteLine($"【{GetPathType(e.FullPath)} 更改】{GetPath(e)}");}
private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e){ Console.WriteLine($"【{GetPathType(e.FullPath)} 创建】{GetPath(e)}");}
private void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e){ Console.WriteLine($"【{GetPathType(e.FullPath)} 重命名】{GetOldPath((RenamedEventArgs)e)} --> {GetPath(e)}");}
private void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e){ Console.WriteLine($"【{GetPathType(e.FullPath)} 删除】{GetPath(e)}");}
/// <summary>/// 获取变动的路径的显示字符串/// </summary>private string GetPath(FileSystemEventArgs e){ if (Configs.IsShowFullPath) { return e.FullPath; }
return e.Name;}
/// <summary>/// 获取原先路径的显示字符串/// </summary>private string GetOldPath(RenamedEventArgs e){ if (Configs.IsShowFullPath) { return e.OldFullPath; }