c# – FileSystemWatcher有一个奇怪的行为
发布时间:2020-12-15 21:20:39 所属栏目:百科 来源:网络整理
导读:我想监视PBX的日志文件以进行更改.我用FileSystemWatcher制作了一个小程序. 现在它变得很奇怪:当我启动程序时,FileSystemWatcher永远不会触发Changed-Event.尽管事实上日志文件确实发生了变化.但是当我在Windows资源管理器中打开日志文件所在的目录时,程序
我想监视PBX的日志文件以进行更改.我用FileSystemWatcher制作了一个小程序.
现在它变得很奇怪:当我启动程序时,FileSystemWatcher永远不会触发Changed-Event.尽管事实上日志文件确实发生了变化.但是当我在Windows资源管理器中打开日志文件所在的目录时,程序按预期工作.但只要资源管理器窗口保持打开状态……什么……? 操作系统:Windows Server 2008 R2 编辑:对不起,这是代码: class Program { static void Main(string[] args) { new LogFileWatcher(@"C:PBXDial.log"); System.Console.Read(); } } public class LogFileWatcher { public string LogFilePath { get; private set; } private DateTime _lastLogFileWriteTime; public LogFileWatcher(string path) { LogFilePath = path; var directoryName = Path.GetDirectoryName(LogFilePath); var fileName = Path.GetFileName(LogFilePath); var fsw = new FileSystemWatcher { Path = directoryName,Filter = fileName }; fsw.Changed += fsw_Changed; fsw.EnableRaisingEvents = true; } private void fsw_Changed(object sender,FileSystemEventArgs e) { // Get and fix the last write time of the log file var fixLastWriteTime = File.GetLastWriteTime(LogFilePath); // Don't do anything when file didn't change since last time if (fixLastWriteTime == _lastLogFileWriteTime) return; Console.WriteLine("File changed on: {0} - ID:{1}",DateTime.Now.ToLongTimeString(),Guid.NewGuid()); // Save last write time of the log file _lastLogFileWriteTime = fixLastWriteTime; } } EDIT2:也许这很重要:PBX Windows服务正在使用日志文件!我可以用记事本打开它. 解决方法
阅读
http://blogs.msdn.com/b/alejacma/archive/2011/03/23/filesystemwatcher-class-does-not-fire-change-events-when-notifyfilters-size-is-used.aspx以获得解释.也许你的情况是一样的.在文件句柄关闭之前,不会触发FW Changed事件.因此,在WindowsService关闭文件之前,您几乎陷入困境.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |