我想监视PBX的日志文件以进行更改.我用FileSystemWatcher制作了一个小程序.
现在它变得很奇怪:当我启动程序时,FileSystemWatcher永远不会触发Changed-Event.尽管事实上日志文件确实发生了变化.但是当我在Windows资源管理器中打开日志文件所在的目录时,程序按预期工作.但只要资源管理器窗口保持打开状态……什么……?
操作系统:Windows Server 2008 R2
编辑:对不起,这是代码:
class Program { static void Main(string[] args) { new LogFileWatcher(@"C:\PBX\Dial.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关闭文件之前,您几乎陷入困境.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。