-->

FileNotFoundException in FileSystemWatcher

2019-08-14 15:45发布

问题:

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()?

回答1:

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 various Directory.Exists() checks before actually performing IO operations.



回答2:

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 the FileSystemWatcher couldn't manage it. So obviously the Directory.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.