Question

I've written a small test application using the .Net FileSystemWatcher to keep an eye on a directory. When I copy a large-ish (a few Mb) file into that directory I get the following events listed (see screenshot - and ignore the Delete event to begin with).

alt text http://robinwilson.homelinux.com/FSW.png

I get a created event (as expected), but then two changed events (about 0.7 seconds apart). Why is this? This would cause major problems in the application I am planning to develop - as I'd try and do things with the file twice (presumably once before it has finished being written to!). Is there anything I can do to stop this happening? From what I've read on StackOverflow and elsewhere, you should just get one changed event once the file has been changed and then closed. Why am I getting two?

Was it helpful?

Solution

According to the documentation (see the first bullet point under Events and Buffer Sizes):

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

OTHER TIPS

Usually the copying program is doing it in blocks, not entire file at once. I don't think you can do anything to avoid this, you will have to adopt your algorithms to deal with this.

You can perform an attempt to open file with exclusive read rights, which should be granted to your program only when other program finished copying and closed file. Otherwise you will get IOException and you can wait for next change. But this doesn't mean you shouldn't deal with multiply change events. Opening text file in Notepad and saving it once in a while will generate change events, but file will not be locked all the time.

Another approach would be to collect touched files for a period of time, and when FileSystemWatcher stops generating events, process all files at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top