58

When I try to set the watcher path to a single file like so:

watcher.Path = filePath1;

I get the error:

The directory name C:\Cromos 3.0\repository\diagnostics\dwm01_2011_06_13__09_03.LXD is invalid.

Can you only set the path to a folder directory?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Jimmy
  • 2,191
  • 6
  • 25
  • 45
  • watcher.Filter will do what you need. – Jay Oct 09 '12 at 10:39
  • @Charleh, I am not sure I agree with that, as FileSystemWatcher also provides a changed event, so you might want to know when a specific file is changed. – Justin Harvey Oct 09 '12 at 10:41
  • 1
    Ok that's true, it's been a while since I've used it - I'm pretty sure I've read that sometimes it can be unreliable when large numbers of changes/files were added/removed etc – Charleh Oct 09 '12 at 11:16

2 Answers2

126

Your error is setting the Path property with a full filename

watcher.Path = Path.GetDirectoryName(filePath1); 
watcher.Filter = Path.GetFileName(filePath1);

should work.

Not related to your proper question, but, of course, to enable the FileSystemWatcher's functionality, it is imperative to set the EnableRaisingEvents property to true.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 2
    makes sense but the 'OnChanged' event isn't being called when I change the file contents. Is it a problem that my filesystemwatcher is inside a class and not 'Form1'? – Jimmy Oct 09 '12 at 11:00
  • You would have to have an instance of that class running, otherwise there will be no filewatcher. – w5l Oct 09 '12 at 11:08
  • 4
    Also note that you need to set `EnableRaisingEvents = true` after setting everything else, otherwise it won't work. – Sheridan Mar 16 '18 at 13:17
7

Yes, but you can watch for specific files by setting the filter property to the filename.

e.g.

watcher.Filter = "dwm01_2011_06_13__09_03.LXD";
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
  • Thanks! Do you know if this will work if I want to watch multiple single pages. i.e. My filesystemwatcher is inside a 'Page' class. Multiple instances of the class = multiple single pages being watched? – Jimmy Oct 09 '12 at 10:45
  • Perhaps, if static. A Page object will unload after it ends its response. – Jon Davis Apr 20 '15 at 20:53