views:

25

answers:

1

Whenever I am subscribing to FileSystemWatcher notification, multiple events are occuring when I create new file or change existing file. Events are occuring in following sequence:

New File

Created

Changed

Changed

Changed

Changed

Changed

Changed

Change

Changed

Deleted

Changed

Rename

Renamed

Delete

Deleted

Rename and Delete are working as expected. Created and Changed are invoked multiple time.

Is there any solution/workaround for getting exact notification when files are added/changed?

+3  A: 

If you look at the SDF source code for the FSW, you'll see it's actually a pretty thin managed shim around the native SHChangeNotifyRegister call with the dwEventMask set to SHCNE_ALLEVENTS. A window handle is passed to the API that then receives callbacks when changes occur and those callbacks are marshalled to the managed events the FSW exposes on the managed side.

Now looking at the callback, it looks like there are 9 event IDs that are handles, four of which raise a Changed event:

  • SHCNE_UPDATEDIR
  • SHCNE_RMDIR
  • SHCNE_UPDATEITEM
  • SHCNE_ATTRIBUTES

So when you create a new file, it's SHCNE_CREATE gives you the Created event, followed by some other callbacks raising several Changed events. Are all of the event args the same on the change events? If they are, you'd have to use the debugger to step through the SDF code to see exactly what is coming in and for which actual callbacks.

The short story here is that the SDF is simply forwarding the events that the OS is giving to it. The reason you see all of these events is because the OS sending them. Exactly why it is sending them may be the way the OS is handling the file, or it may even be specific to the file system driver you're using (i.e. on anotehr device it might be slightly different, or even on another disk in the same device).

The workaround I think would be to look at the event args and "group" the events for the same file name that happen in quick succession. For example if you get a bunch of Changed and a Created event for the same file name in the same folder all within a second, then it's a good bet that it was a file creation.

ctacke
Catching events and determining duplicate events that occur within a second seems to be a hack. Is there any better solution to it?
Let me Ask
If I could think of a better solution, I would have offered it.
ctacke