I need to ensure that all pending FileSystemWatcher events are processed before executing my operation. Is there any way to do this?
The FileSystemWatcher uses a buffer in non-paged memory to store the file system events. As you handle each event it is removed from this buffer, freeing space for new events.
It is not a queue or list that can grow indefinitely in size. If there are many events in a short time, the buffer is filled and then an Error event is thrown. So you don't have the ability to flush this buffer.
If you want to ensure the buffer is empty before you start handling events, the simplest approach would be to create a new FileSystemWatcher and start watching just before you need it. However you should be careful you don't create too many simultaneous watchers due to the reliance each has on storing the buffer in non-paged memory.
If you're watching a file, open it for writing to lock it so that nobody else can access it and thus generate any new events. Then wait for a millisecond or so. Ugly? Yes.
My solution for this task.. So far it looks ok.
while (true)
{
WaitForChangedResult res = watcher.WaitForChanged(WatcherChangeTypes.All, 1);
if (res.TimedOut)
break;
}