NTS
NTS

Reputation: 11

FileSystemWatcher for directory with items with paths too long

I have a Windows application that manages files and directories with long paths. I have a FileSystemWatcher to monitor the parent directory and all of its children, but I have problems because when the item has more than 200 characters (more or less) the app don't receive the events for it.

For example, when there is one file or directory with a long path, the app don't receive the event when this item is deleted or renamed. With all the rest of elements with short paths the FileSystemWatcher works fine and the app is be able to manage the events received.

Anybody know another form to monitor elements with long paths? Any FileSystemWatcher or similar that supports long paths?

Thanks in advance

Upvotes: 1

Views: 848

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

It is likely you are overflowing the buffer. The default buffer size for the FileSystemWatcher is only 8 Kb and long file names can really eat into that. See here:

The system notifies the component of file changes, and it stores those changes in a buffer the component creates and passes to the APIs. Each event can use up to 16 bytes of memory, not including the file name. 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 can prevent missing file system change events. However, increasing buffer size is expensive, because it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties to filter out unwanted change notifications.

Also see the note here:

Avoid watching files with long file names, because a long file name contributes to filling up the buffer. Consider renaming these files using shorter names.

And this:

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

So a single operation with a long file name might fire multiple events each with the long file name consuming chunks of your buffer.

An alternative is to set up a timer to poll the directory yourself at some interval (depending on the needs of your app) and compare with the last poll to detect what has changed.

This question has some discussion on the topic.

Upvotes: 2

Related Questions