munna
munna

Reputation: 229

FileNotFoundException in FileSystemWatcher

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

Upvotes: 1

Views: 3626

Answers (4)

Greg Z.
Greg Z.

Reputation: 1566

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 :)

Upvotes: 1

Lucca Ferri
Lucca Ferri

Reputation: 1347

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.

Upvotes: 4

Dzik
Dzik

Reputation: 55

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.

Upvotes: 2

Neil Barnwell
Neil Barnwell

Reputation: 42125

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.

Upvotes: 3

Related Questions