views:

133

answers:

1

Does anyone have any ideas how I can reliably disable a FileSystemWatcher object when my application makes changes to the files in the directory, so that I am only watching for external changes to the directory?

I've tried setting EnableRaisingEvents to false immediately before performing a write and setting it back to true immediately after, but it seems this method is not reliable, and occasionally I still get the event firing.

The only other thing I can think of is to wait a small amount of time after performing the write to let the OS finish up the modification of the directory before re-enabling the FSW, but that seems hackish and I don't like it.


To add to the problem, the directory consists of potentially many files, the identities of which are beyond my knowledge and control, so I can't just wait for the event to fire for a specific file and then ignore it. There could be any number of FSW events firing after a single modification (because of the potentially many files getting updated).

+2  A: 

You cannot do this using the .NET API.

As multiple users pointed out, you'll probably be better off maintaining a list of changes you make and subtract them from the changeset you observe.

You can also use Win32-level API, which gives you a PID for the process making the change if I'm not mistaken (not sure about this, I've written a driver before which did this (and more) inside the kernel space).

UPDATE: I called someone on the team I worked with on this project, and they confirm we had the PID in kernel space only.

Shachar
Now that would be great if I could determine the process--then I could just check if it was me or not. Do you recall the name of the hook or function in Win32?
chaiguy
Shachar, this doesn't appear to be the case. I see no mention of any way to obtain a process id using FindFirstChangeNotification or ReadDirectoryChangesW.Now if I could somehow receive an event when my process obtains a file handle, I could check to see if that file was in the directory and ignore changes to it, but I can't find any way to do that, either. :(
chaiguy