开发者

FileSystemWatcher has a strange behaviour

开发者 https://www.devze.com 2023-03-19 00:49 出处:网络
I want to monitor a log file of our PBX for changes. I made a small program that does just that with a FileSystemWatcher.

I want to monitor a log file of our PBX for changes. I made a small program that does just that with a FileSystemWatcher.

Now it's getting strange: The FileSystemWatcher never fires the Changed-Event when I simply start the program. Despite the fact that the log file really has changed. But when I open the directory in the Windows Explorer where the log file is located, the program works as expected. But only as long as the Explorer Window stays open... what the..?

Operating System: Windows Server 2008 R2

EDIT: Sorry, here is the code:

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
        i开发者_如何学编程f (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: Maybe this is important: The log file is in use by the PBX Windows-Service! I can open it with Notepad though.


For optimization reasons, the FileStream.Flush()-Method doesn't flush metadata anymore (Vista and later Microsoft operating systems). Therefore the FileSystemWatcher gets no file notification and won't fire the 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

0

精彩评论

暂无评论...
验证码 换一张
取 消