using Aitex.Core.RT.Log; using System; using System.Collections.Generic; using System.IO; namespace Aitex.Core.Util { /// /// 文件变更监视器管理器。 /// public class FileSystemWatcherManager : Singleton { #region Variables private readonly Dictionary> _dicWatches = new(); #endregion #region Properties /// /// 返回注册的文件监视器的总数。 /// public int Count => _dicWatches.Count; #endregion #region Methods /// /// 注册一个监视器用于监视指定文件内容的变更。 /// /// 包含完整路径的文件名。 /// 当文件内容发生变化时执行的回调函数。 public virtual void Register(string fullFileName, Action CallbackOnFileChanged) { if(File.Exists(fullFileName)) { var path = Path.GetDirectoryName(fullFileName); var fn = Path.GetFileName(fullFileName); var watcher = new FileSystemWatcher(path, fn); watcher.Changed += OnChanged; watcher.IncludeSubdirectories = false; watcher.EnableRaisingEvents = true; _dicWatches.Add(watcher, CallbackOnFileChanged); LOG.Info($"New file watcher added for {fullFileName}"); } else { LOG.Error($"Error to add file watcher for {fullFileName}, file not exists"); } } private void OnChanged(object sender, FileSystemEventArgs e) { if (sender is FileSystemWatcher watcher) { LOG.Info($"{e.FullPath} changes detected."); if(_dicWatches.TryGetValue(watcher, out var action)) action(e.FullPath); } } #endregion } }