I am working on a C# program that needs to use the FileSystemWatcher
class so it will be notified when new files are created. As part of the initialization, the program scans the directory so it can process any files that already exist in it. This is all working fine.
However, in a discussion with another developer, we started questioning whether this will always work. Are there conditions under which the FileSystemWatcher
will miss the creation of files? If so, what are these conditions?
In order to handle this scenario, we would just run the code in our initialization process that scans the directory periodically, but how likely is it for the FileSystemWatcher
to miss files?
Note that a FileSystemWatcher may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines: Increase the buffer size by setting the InternalBufferSize property. Avoid watching files with long file names, because a long file name contributes to filling up the buffer.
FileSystemWatcher is "known to be unreliable". In simple words, it doesn't work well. If the data size of the collected watcher events exceeds the size of the buffer created by FileSystemWatcher, the events that overflow are lost, and reliable exceptions are not raised.
Nope, filesystemwatchers run on their own thread.
FileSystemWatcher
will not usually miss files. However:
ReadDirectoryChangesW
, it only detects changes to the file's directory entry, not changes to the file itself. Most changes to the file will update the directory entry, but there are a few exceptions (see this article).Other pitfalls:
Moved
. If you move a file from a directory to another, you will receive two notifications : Deleted
and Created
SOMETH~1.TXT
instead of Something.txt
)Changed
events can occur several times for the same file; you need to handle the duplicates yourselfThe FileSystemWatcher
is not supposed to miss any file, however, if your file processing is long, you should queue the events and treat them in a different thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With