开发者

FileNotFoundException in FileSystemWatcher

开发者 https://www.devze.com 2023-01-21 16:30 出处:网络
I am using a FileSystemWatcher on a directory and added its event handlers, set its EnableRaisingEvents=true; and IncludeSubdirectories=false; and added NotifyFilters.

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 开发者_JAVA技巧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 various Directory.Exists() checks before actually performing IO operations.


Just out of stupidity, I googled it before thinking.

In my case, Path was being defined after EnableRaisingEvents.

e.g. won't throw an exception:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
//...
watcher.EnableRaisingEvents = true;

This will:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.EnableRaisingEvents = true;
//...
watcher.Path = @"C:\";

So. since I like to fail-fast instead of letting the next one figure out what the hell is happening, I modified that after path declaration:

var watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\me";
if (string.IsNullOrWhiteSpace(watcher.Path))
    throw new InvalidOperationException($"You must define a path.");
if (!Directory.Exists(watcher.Path))
    throw new InvalidOperationException($"Directory {watcher.Path} does not exist.");
watcher.EnableRaisingEvents = true;

Stupid issue, but at least I gave some quirky fail-fast solution.


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.


For me it was some mystery where, I guess a directory was named with some invalid character(s). Directory.Exists(watchDirectory) would return true, but the FileWatcher would blow up with the error above. The "fix" was to delete the directory and recreate it with the same name :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号