Thursday, October 13, 2011

Not happy with .NET's FileSystemWatcher

I created a Windows Service to watch for a specific file, which heavily relies on the FileSystemWatcher class. I'm not sure it was worth the hassle over using Timer to just check for the file at a certain interval.

FileSystemWatcher fires an event when a file is created, which is great, except that it seems that it fires the millisecond the file starts to be created (acting more like a "Creating" event...). This was causing problems for me, because my relatively small file was apparently still being written to while I was trying to send it as an attachment and subsequently delete it. There is no "ReallyDoneBeingCreated" event. There is a "Change" event, but that was causing me even more problems.

I ended up adding "Thread.Sleep(30000)" (waits for 30 seconds) after it sees there is a new file. This is crap. I HATE doing stuff like this, but it works, since it takes about a second to create the file in my case. The only other thing I could think of doing is having some crazy recursive try/catch loop that fails, tries again and again until it succeeds. This is ugly, too, but would probably be better if the file size was unknown.

My kludge is upsetting me to the point that I may just end up re-writing the code to use a timer interval to check for a new file, but that is a bit backwards,  too. Can't win. Anybody know of a better way of doing this?

No comments: