咨询区
PaulB:
请问在 C# 中如何实现当一个磁盘文件的变更,让我的程序马上能感知到?
回答区
Dirk Vollmar:
在 C# 中有一个 FileSystemWatcher
类,它专门用来做文件的变更感知,大概有如下四类通知事件:
Changed
文件内容变更通知,参考连接:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.changed.aspx
Created
文件创建变更通知,参考连接:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created.aspx
Deleted
文件删除变更通知,参考连接:https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.deleted?redirectedfrom=MSDN&view=net-5.0
Renamed
文件重命令通知,参考连接:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.renamed.aspx
下面的代码就是用来监控 D:\test
目录下的所有 txt 文件。
class Program{static void Main(string[] args){CreateFileWatcher(@"D:\test");Console.ReadLine();}public static void CreateFileWatcher(string path){// Create a new FileSystemWatcher and set its properties.FileSystemWatcher watcher = new FileSystemWatcher();watcher.Path = path;/* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite| NotifyFilters.FileName | NotifyFilters.DirectoryName;// Only watch text files.watcher.Filter = "*.txt";// Add event handlers.watcher.Changed += new FileSystemEventHandler(OnChanged);watcher.Created += new FileSystemEventHandler(OnChanged);watcher.Deleted += new FileSystemEventHandler(OnChanged);watcher.Renamed += new RenamedEventHandler(OnRenamed);// Begin watching.watcher.EnableRaisingEvents = true;}// Define the event handlers.private static void OnChanged(object source, FileSystemEventArgs e){// Specify what is done when a file is changed, created, or deleted.Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);}private static void OnRenamed(object source, RenamedEventArgs e){// Specify what is done when a file is renamed.Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);}}
当然如何你想监控 D:\test
下包括子目录的 txt 文件,可以配置 IncludeSubdirectories
属性,参考如下代码:
watcher.IncludeSubdirectories = true;
点评区
FileSystemWatcher 非常强大,在 .NETCore 中实现对 appsettings 的监控,用的就是它作为底层实现。