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?
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 yourself