Search code examples
c#file-monitoring

FileSystemWatcher skips Created-events


I have a FileSystemWatcher that checks multiple directories if there are any files created.

            ((System.ComponentModel.ISupportInitialize)(FileMonitor)).BeginInit();
            FileMonitor.EnableRaisingEvents = true;
            FileMonitor.Created += new FileSystemEventHandler(FileMonitor_Created);
            FileMonitor.Path = Path.ToString();
            FileMonitor.IncludeSubdirectories = true;
            FileMonitor.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes;
            ((System.ComponentModel.ISupportInitialize)(FileMonitor)).EndInit();

For some reason the FileMonitor_Created event is not always fired when running the application, even though it should. It feels random...

However, if I put a breakpoint at the FileMonitor_Created method, it works perfectly: The event fires everytime it should, if the breakpoint is set.

I've tried setting an InterBufferSize for the FileMonitor, but that had no effect.

Update

I added the Changed event to the Filemonitor and gave it the same handler as for the Created event. Somehow it works now, although the file is actually created, not changed.

I'm still curious why it always worked 'the old way' when setting a breakpoint.


Solution

  • How many changes are you making?

    The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

    Taken from MSDN