c# 文件监听

it2024-11-13  4

public class FileListenerServer { private FileSystemWatcher _watcher; public FileListenerServer() { } /// <summary> /// /// </summary> /// <param name="path">监听目录</param> public FileListenerServer(string path) { try { this._watcher = new FileSystemWatcher(); _watcher.Path = path;//监视目录 _watcher.Filter = "*.config";//过滤文件 _watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName; _watcher.IncludeSubdirectories = true;//监视子目录 _watcher.Created += new FileSystemEventHandler(FileWatcher_Created); _watcher.Changed += new FileSystemEventHandler(FileWatcher_Changed); _watcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted); _watcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed); } catch (Exception ex) { Console.WriteLine("Error:" + ex.Message); } } public void Start() { this._watcher.EnableRaisingEvents = true; Console.WriteLine("文件监控已经启动..."); } public void Stop() { this._watcher.EnableRaisingEvents = false; this._watcher.Dispose(); this._watcher = null; } protected void FileWatcher_Created(object sender, FileSystemEventArgs e) { Console.WriteLine("新增:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name); } protected void FileWatcher_Changed(object sender, FileSystemEventArgs e) { if (e.Name.Equals("App.config")) { var configPath = (AppDomain.CurrentDomain.BaseDirectory + "App.config"); ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var configuartion = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var value = configuartion.AppSettings.Settings["key"].Value; } Console.WriteLine("修改:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name); } protected void FileWatcher_Deleted(object sender, FileSystemEventArgs e) { Console.WriteLine("删除:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name); } protected void FileWatcher_Renamed(object sender, RenamedEventArgs e) { Console.WriteLine("重命名: OldPath:{0} NewPath:{1} OldFileName{2} NewFileName:{3}", e.OldFullPath, e.FullPath, e.OldName, e.Name); } }

 

最新回复(0)