FileSystemWatcher OnCreated only firing for first

2020-04-08 06:42发布

I have a FileSystemWatcher that I would like to fire an OnCreated event for every folder copied into the watched directory. Several folders will be copied into this watched directory at once, manually.

Currently it is only firing the event for the first folder copied.
So if I'm watching folder X and select folders A,B,C in windows explorer and copy them into X, OnCreated is fired for A but not B or C.

This is my code that I'm using to set up the FileSystemWatcher:

watcher = new System.IO.FileSystemWatcher(watchPath);            
watcher.InternalBufferSize = 32768;
watcher.IncludeSubdirectories = true;
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | 
                       NotifyFilters.CreationTime | NotifyFilters.LastWrite;


watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;

and here is my OnCeated method

void OnCeated(object sender, FileSystemEventArgs e)
{            
    XDocument xmlDoc = BeginImport(e.FullPath); 
}

Any idea why this is only firing the event for the first folder copied into the watched directory?

1条回答
做自己的国王
2楼-- · 2020-04-08 07:09

From the documentation:

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.

It seems to be an internal limitation.

I believe the act of pasting all three folder at once is considered "many changes in a short time" -- can you use the NotifyFilter and leave out some events?

查看更多
登录 后发表回答