FileSystemWatcher有一个奇怪的行为

时间:2011-07-08 09:44:15

标签: c# file filesystemwatcher

我想要监控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服务正在使用日志文件!我可以用记事本打开它。

2 个答案:

答案 0 :(得分:1)

阅读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关闭文件之前,您几乎陷入困境。

答案 1 :(得分:0)

出于优化原因,FileStream.Flush() - Method不再刷新元数据(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