Watching the FileSystem

Inspired by a blog entry by The Powershell Guy.

This code example watches the filesystem using System.IO.FileWatcher. It notifies you of changes via a callback:

You will see output like:

NOTES: The events are raised on another thread. The Changed event is raised when changes are made to the size, system attributes, last write time, last access time, or security permissions of a file or directory in the directory being monitored. 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.

If you want to include subdirectories of a directory you are watching, you can set the IncludeSubdirectories property to True…

By default a FileSystemWatcher watches for any changes in a directory. If you only want to watch an individual file, or files with specific extensions, then you need to use the Filter Property. The following code will only watch for changes in a file called ‘data.txt’:

The next example watches for changes in any text files:


Original URL: Licensed under CC BY 3.0

Wayback Machine: