Debugging FileSystemWatcher.Created

· Ben’s Blog

Today's debugging adventure involved an ActiveX control that uses FileSystemWatcher to watch for files to be copied into a folder and then spits out some log messages onto the page. The behavior I was seeing was that sometimes when I copied a valid file into the watched folder, Internet Explorer would crash. After putting in additional logging, I found that the code was throwing an IOException. Searching for how to really open a file read-only, I learned about the FileShare parameter.

This didn't fix my problem, though. After some more fuddling around and talking to coworkers, I realized that the problem may be more related to the FileSystemWatcher.Created event. It gets raised when the file first gets created, and if you try to access it before it's done, you'll get an IOException. The best solution I could find is to simply catch that exception, sleep, and try again. I wrote some code like this:

 1    public static bool IsLockAvailable(string filePath)
 2    {
 3        try
 4        {
 5            using (File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
 6            {
 7                return true;
 8            }
 9        }
10        catch (IOException)
11        {
12            return false;
13        }
14    }
15
16    public static void WaitForLockOnFile(string filePath)
17    {
18        if (File.Exists(filePath))
19        {
20            while (!IsLockAvailable((filePath)))
21            {
22                Thread.Sleep(50);
23            }
24        }
25    }

And called WaitForLockOnFile() before trying to do anything with the file in my Created handler.