FileSystemWatcher有一个奇怪的行为

本文关键字:有一个 FileSystemWatcher | 更新日期: 2023-09-27 18:01:27

我想监视PBX的日志文件以查看更改。我用FileSystemWatcher编写了一个小程序来完成这个任务。

现在它变得奇怪了:当我简单地启动程序时,FileSystemWatcher从未触发Changed -事件。尽管日志文件确实发生了变化。但是,当我在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-Service使用!我可以用记事本打开

FileSystemWatcher有一个奇怪的行为

出于优化的原因,FileStream.Flush()-方法不再刷新元数据(Vista和以后的Microsoft操作系统)。因此,FileSystemWatcher不会收到文件通知,也不会触发Changed-Method。

http://connect.microsoft.com/VisualStudio/feedback/details/94772/filestream-flush-does-not-flush-the-file-in-the-correct-way-to-work-with-filesystemwatcher-or-native-readdirectorychangesw