您的位置:首页 > 其它

使用 FileSystemWatcher 侦听文件

2006-09-10 11:45 453 查看

private ConfigureAndWatchHandler(ILoggerRepository repository, FileInfo configFile)




...{


// Create a new FileSystemWatcher and set its properties.


FileSystemWatcher watcher = new FileSystemWatcher();




watcher.Path = m_configFile.DirectoryName; //设定侦听文件的目录


watcher.Filter = m_configFile.Name; //设定指定的侦听文件,不设置,则侦听整个目录




// Set the notification filters 设定侦听文件的哪些属性


watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;




// Add event handlers. OnChanged will do for all event handlers that fire a FileSystemEventArgs


watcher.Changed += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);


watcher.Created += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);


watcher.Deleted += new FileSystemEventHandler(ConfigureAndWatchHandler_OnChanged);


watcher.Renamed += new RenamedEventHandler(ConfigureAndWatchHandler_OnRenamed);




// Begin watching. 设定是否启用侦听


watcher.EnableRaisingEvents = true;




//由于修改了侦听文件,会激发2次watcher的Changed事件,所以用Timer来延迟主处理


// Create the timer that will be used to deliver events. Set as disabled


_timer = new Timer(new TimerCallback(OnWatchedFileChange), null, Timeout.Infinite, Timeout.Infinite);


}




private Timer _timer;


private const int TimeoutMillis = 500;


private void Watcher_Changed(object sender, FileSystemEventArgs e)




...{


// Deliver the event in TimeoutMillis time


// timer will fire only once


_timer.Change(TimeoutMillis, Timeout.Infinite);


}


private void OnWatchedFileChange(object state)




...{


try




...{


this._isReload = true;


this._mappers = this.CetMappers();


}




catch ...{}


finally




...{


this._isReload = false;


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: