Skip to content

FileSystemWatcher

by Alex Peck on July 26th, 2009

The FileSystemWatcher class provides a mechanism for raising events based on changes to the file system (files or directories).

The Filter property allows you to specify which file(s) you are interested in watching. The NotifyFilter allows you to specify which events to watch for (created/modified/deleted etc.). You can also specify whether or not to IncludeSubdirectories. Using these properties correctly ensures that a manageable amount of file system events are raised (see below).

FileSystemWatcher events use three delegate types:

  • Changed, Created, Deleted events use FileSystemEventHandler
  • Renamed events use a RenamedEventHandler
  • Error events use a ErrorEventHandler

You should minimise the work performed in these event handlers, otherwise you can impact the number of events you may handle.

There is also a synchronous WaitForChanged method which returns a structure containing changes.

Caveats

I would advise setting the error handler first, otherwise you can get silent failures when setting other properties.

Generally, it is not advisable to use FileSystemWatcher on network drives. If/when a network outage occurs the watcher ceases to function, a simple workaround is given here.

The underlying Win 32 ReadDirectoryChangesW function will fail with ERROR_INVALID_PARAMETER if the buffer length is greater than 64 KB and the application is monitoring a directory over a network. This is due to a packet size limitation with the underlying file sharing protocols.

Furthermore, there is no guarantee that you will recieve notification of every change under heavy load scenarios. This is compounded for network shares, since you have a smaller buffer size limitation. See this page for a detailed explanation.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS