Why FileSystemWatcher generates several change events when copying a file to a directory

I wrote a small test application using the .Net FileSystemWatcher to keep track of the directory. When I copy a large file (several MB) to this directory, I get the events listed below (see. Screenshot - and ignore the "Delete" event).

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

I get the generated event (as expected), but then two changed events (for about 0.7 seconds). Why is this? This will cause serious problems in the application that I plan to develop - as I would try to do something with the file twice (presumably the time he finished writing!). Is there anything I can do to stop this? From what I read in StackOverflow and elsewhere, you should just get one changed event after the file has been modified and then closed. Why am I getting two?

+4
source share
2 answers

According to the documentation (see the first marker in the section Events and buffer sizes):

General file system operations can lead to several events. For example, when a file moves from one directory to another, several OnChanged events and some OnCreated and OnDeleted events can be raised. Moving a file is a complex operation consisting of several simple operations, so several events occur. Similarly, some applications (such as antivirus software) may trigger additional file system events detected by FileSystemWatcher.

+11
source

Typically, a copy program does this in blocks, and not in a complete file at the same time. I do not think that you can do everything to avoid this, you will have to accept your algorithms to deal with it.

You can try to open a file with exclusive read rights, which should be granted to your program only when another program has finished copying and closed the file. Otherwise, you will get an IOException, and you can wait for the next change. But this does not mean that you should not deal with multiple change events. Opening a text file in Notepad and saving it once in a while will generate change events, but the file will not be locked all the time.

Another approach is to collect the affected files for a certain period of time, and when FileSystemWatcher stops generating events, process all the files at once.

+2
source

Source: https://habr.com/ru/post/1277488/


All Articles