I am using a FileSystemWatcher
on a directory and added its event handlers, set its EnableRaisingEvents=true;
and IncludeSubdirectories=false;
and added NotifyFilters
.
While running the application if I create new folders in the specified directory sometime I get
FileNotFoundException : "An error occurred while reading a directory". System.IO.FileSystemWatcher.StartRaisingEvents() System.IO.FileSystemWatcher.set_EnableRaisingEvents(Boolean value)
What can be root cause of the problem?
What is StartRaisingEvents()
?
This is typically because the
FileSystemWatcher
can be unreliable. The folder may not "fully" exist when you get the events. You may need to retry with sufficient pauses and do variousDirectory.Exists()
checks before actually performing IO operations.I've got quite the same problem and finally I found out that the problem was with the path.
The
Directory.Exist()
give answer that the directory exist... even if the path got a empty char in the end of the string but theFileSystemWatcher
couldn't manage it. So obviously theDirectory.Exist()
trim the path but the Watcher don't. In my case removing of the empty chars solve the problem.Hopefully it could help somebody.