The FileSystemWatcher class is part of the .NET framework and is used to watch for changes in directories or files. For programs that need to monitor particular files, this class is perfect and very helpful. I wrote a program to parse a log file and used the FileSystemWatcher class to monitor the log file and raise an event when a new line is added to the log. My code worked great on Windows XP but after upgrading to Windows Vista I noticed that the FileSystemWatcher stopped working.
The FileSystemWatcher seems to have a bug on Vista where if the file is currently open by another program (as in the case with real-time log files) then it will not notice any changes made to the file. From my own experience I found that if I used Windows Explorer to browse to the log folder (or refreshed the folder if Windows Explorer was already there) then the FileSystemWatcher would finally pick up the changes. I experienced this bug on .NET 2.0 so I’m not certain if it exists in .NET 1.1 or 3.0 on Vista.
I eventually came up with a workaround for my particular program. You basically need to add your own timer which will check the file for modifications. You could create your own code to act as a FileSystemWatcher and look for new lines added. But this involves rewriting your code. Another solution is to use a FileInfo object to help the FileSystemWatcher. In my program I created a timer that would fire once per second. The timer creates a FileInfo object for the same log file that the FileSystemWatcher is currently watching. It will then call the Refresh method of the FileInfo object. Calling the Refresh method will cause the FileSystemWatcher to notice any changes to the file and raise the proper event like it is supposed to. Since the timer code is so short there is no noticeable performance increase. This is the preferred workaround since you don’t need to modify any of your existing code. Additionally, whenever this bug is fixed you can just remove the timer and you will not have to rewrite any code. If your program also runs on other operating systems (like XP or 2003 server) then you could probably add some additional code to check which operating system is running and only use the timer code if it is running on Vista.
I discussed this particular bug with others on the MSDN forums at: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1569013&SiteID=1
Recent Comments