监听文件夹
目的
由于一些需求, 需要对关心的文件夹下面的文件做时时的监视包括改名、新增、删除、修改等, 因为文件夹文件数目不少每次重新扫描整个文件将非常的浪费时间.
方案
使用FileSystemWatcher来监听这些感兴趣的变动
示例代码
using System; using System.IO; namespace FileSystemWatcherDemo { class Program { static void Main(string[] args) { FileSystemWatcher fsw = new FileSystemWatcher(); fsw.Path = @"./"; // 不支持使用多个筛选器 // *.* 所有文件(默认值 空字符串("")还会监视所有文件 // *.txt 扩展名为 "txt" 的所有文件 // *recipe.doc 所有以 "食谱" 结尾且扩展名为 "doc" 的文件 // win*.xml 所有以 "win" 开头且扩展名为 "xml" 的文件 // ? 任意单字符匹配 fsw.Filter = "*app*.json"; fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; fsw.Changed += new FileSystemEventHandler(OnChanged); fsw.Created += new FileSystemEventHandler(OnCreated); fsw.Deleted += new FileSystemEventHandler(OnDeleted); fsw.Renamed += new RenamedEventHandler(OnRenamed); fsw.EnableRaisingEvents = true; Console.WriteLine("Press 'q' to quit the sample."); while (Console.Read() != 'q') ; } private static void OnRenamed(object sender, RenamedEventArgs e) { Console.WriteLine($"File Name From {e.OldFullPath} To {e.FullPath}."); } private static void OnDeleted(object sender, FileSystemEventArgs e) { Console.WriteLine($"File {e.FullPath} Removed."); } private static void OnCreated(object sender, FileSystemEventArgs e) { Console.WriteLine($"New File {e.FullPath} Created."); } private static void OnChanged(object sender, FileSystemEventArgs e) { Console.WriteLine($"File {e.FullPath} Changed."); } } }
示例输出
Press 'q' to quit the sample. File Name From ./New.docx To ./New-app-.json. File Name From ./新建 Text Document.txt To ./新建 app Text Document.json. File Name From ./新建 Text Document.txt To ./新建 App 2.json. File ./New-app-.json Changed. File ./New-app-.json Changed. File Name From ./新建 App 2.json To ./App 2.json. New File ./新建 app Text Document - 副本.json Created. File ./新建 app Text Document - 副本.json Changed. New File ./App 2 - 副本.json Created. File ./App 2 - 副本.json Changed. File ./App 2 - 副本.json Removed. File ./App 2.json Removed. File ./New-app-.json Removed. File ./新建 app Text Document - 副本.json Removed. File ./新建 app Text Document.json Removed.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
2018-05-28 Easyloggingpp的使用
2018-05-28 Dapper简介