FileSystemWatcher has strange behavior

I want to track the log file of our PBX for changes. I made a small program that does this only with FileSystemWatcher .

Now it gets weird: FileSystemWatcher never starts Changed -Event when I just run the program. Although the log file has really changed. But when I open the directory in Windows Explorer, where the log file is located, the program works as expected. But only as long as the browser window remains open ... what is it ...?

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 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: Perhaps this is important: the log file is used by the Windows PBX service! I can open it using Notepad.

+4
source share
2 answers

For optimization reasons, FileStream.Flush () - the method no longer hides metadata (Vista and later Microsoft operating systems). Therefore, FileSystemWatcher does not receive file notifications and does not start 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
source

Read http://blogs.msdn.com/b/alejacma/archive/2011/03/23/filesystemwatcher-class-does-not-fire-change-events-when-notifyfilters-size-is-used.aspx for an explanation . Perhaps your case is the same. The FW Changed event will not be fired until the file descriptor is closed. Therefore, until WindowsService closes the file, you are very stuck.

+1
source

All Articles