3

I am attempting to monitor a folder (and its sub-folders) for changes. However, my handler event is never executed. I am using the following code:

FileSystemWatcher m_Watcher = new FileSystemWatcher();
m_Watcher.Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Portal 2 Map Installer/"; 
m_Watcher.Filter = "";
m_Watcher.NotifyFilter = NotifyFilters.LastAccess |
             NotifyFilters.LastWrite |
             NotifyFilters.FileName |
             NotifyFilters.DirectoryName;
m_Watcher.IncludeSubdirectories = true;
m_Watcher.Changed += new FileSystemEventHandler(OnFolderChange);
m_Watcher.EnableRaisingEvents = true;

Help please!

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
YoshieMaster
  • 257
  • 3
  • 5
  • 13
  • That code looks correct to me. The problem must lie elsewhere. What type of file system are you trying to watch? This doesn't work with FAT32 partitions, for example. – Cody Gray - on strike May 20 '11 at 10:57
  • I think I've figured it out! For some reason my Form1_Load event is not triggering, which is where I do all of the initialisation. Now to track down why. – YoshieMaster May 20 '11 at 11:14
  • Alright, got it working! Now does anyone know how to stop the events being triggered three times? I get the created event triggered, then two changed events. – YoshieMaster May 20 '11 at 11:16
  • @Yoshie: You should set properties like this in the constructor: `public Form1()`, rather than in the `Load` event handler method. – Cody Gray - on strike May 20 '11 at 11:22
  • 1
    You can't stop the event being triggered several times, so you have to work around that. See http://stackoverflow.com/questions/449993/vb-net-filesystemwatcher-multiple-change-events for some suggestions. – sgmoore May 20 '11 at 11:48
  • If you are writing for windows 7 ... there is a similar filesystem event watcher in the win7api codepack you may want to have a look at – MaLio May 20 '11 at 15:26

2 Answers2

0

Create a handler for the on error event and see what it says:

  m_Watcher.Error += new ErrorEventHandler(OnError);
Hogan
  • 69,564
  • 10
  • 76
  • 117
0

There are some notes on the Changed event handler :

The Changed event is raised unexpectedly when a file is renamed, but is not raised when a directory is renamed. To watch for renaming, use the Renamed event.

So it would be prudent to handle the Renamed event as well (at the least).

ChrisF
  • 134,786
  • 31
  • 255
  • 325