FileSystemWatcher to watch UNC path

nickfinity picture nickfinity · Jun 27, 2012 · Viewed 38.2k times · Source

There are no shortage of questions on this topic, but I'm still having trouble. Here is my situation. I've got a service that I need to watch a path that is specified in the config file. It works great when I used a local drive.

However, when I change it to something like \\server2\secondary\temp\watch_folder the service does not start. The error in the log is

The directory name \\server2\secondary\temp\watch_folder is invalid.

If I copy that directly into Windows Explorer the folder opens fine. If I take my code and paste it into an old Winforms app it works fine. I've tried all of the "Log On As" accounts. I set it to use the Administrator account, but still no dice.

Here is my code:

_watcher = new FileSystemWatcher();
_watcher.Path = ConfigurationManager.AppSettings["WatchFolder"];
_watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
_watcher.Filter = "*.txt";
_watcher.Created += new FileSystemEventHandler(OnCreated);
_watcher.Error += new ErrorEventHandler(OnError);
_watcher.EnableRaisingEvents = true;

Any ideas? I'm at a loss and at this point I think I've been staring at it too long. I sincerely appreciate any help.

Thanks, Nick

EDIT Here is the exception:

Service cannot be started. System.ArgumentException: The directory name \server2\Secondary\temp\watch_folder is invalid.
at System.IO.FileSystemWatcher.set_Path(String value)
at FileWatcher.FileWatcher.Watch()
at FileWatcher.FileWatcher.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

Answer

Marco Medrano picture Marco Medrano · Jun 27, 2012

I just tried this:

var _watcher = new FileSystemWatcher();
_watcher.Path = @"\\10.31.2.221\shared\";
_watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
_watcher.Filter = "*.txt";
_watcher.Created += new FileSystemEventHandler((x, y) =>Console.WriteLine("Created"));
_watcher.Error += new ErrorEventHandler( (x, y) =>Console.WriteLine("Error"));
_watcher.EnableRaisingEvents = true;
Console.ReadKey();

That works without problems, however i replicated your exception just when:

  • The running user doesn't have permissions to read the remote folder.
  • The remote folder doesn't exist.

Your problem surely is related with permissions, I think that the running user doesn't have the permissions needed.

Another thing that you can try is map the remote folder to one local.

Execute this in the cmd:

NET USE Z: \\server2\Secondary\temp\watch_folder /user:Domain\UserName Password

Then in your code:

_watcher.Path = @"Z:\";