Skip to content

Using .NET to Monitor a Directory for Changes

Robert Greiner
Robert Greiner
1 min read

.NET's FileSystemWatcher class can soothe the paranoid control freak in all of us by monitoring a specified folder for different types of file system changes.

The Code

FileSystemWatcher watcher = new FileSystemWatcher(@"D:\test");

The core of is application is .NET's FileSystemWatcher class which monitors directories for file system changes.

watcher.IncludeSubdirectories = true;watcher.Filter = "";

Tells the FileSystemWatcher object to include changes in subdirectories and raise events on every type of file.

An empty string for the filter will match every file and folder in the watched directory. File types and names can also be added to the filter to create a more fine grained watch.

watcher.Renamed += new RenamedEventHandler(renamed);watcher.Deleted += new FileSystemEventHandler(changed);watcher.Changed += new FileSystemEventHandler(changed);watcher.Created += new FileSystemEventHandler(changed);

Sets the types of file system events the FileSystemWatcher object will respond to. The four possible (and self-explanatory) events are: Renamed, Deleted, Changed, and Created. Each EventHandler takes the method to be executed on that particular event as a paramater in its constructor.

watcher.EnableRaisingEvents = true;

The final piece of the puzzle is to finally tell the FileSystemWatcher to start raising events on the specified directory. Once this statement is executed, we will have a live directory watcher.

Please consider subscribing, it's free.
Technology

Robert Greiner Twitter

Professional optimist. I write a weekly newsletter for humans at the intersection of business, technology, leadership, and career growth.


Related Posts

Members Public

Navigating the Upside Down as a Technology Leader

Ideas for leading technology organizations with confidence and creativity.

Navigating the Upside Down as a Technology Leader
Members Public

Artist for a Day

The future of creative output is multiplied by AI.

Artist for a Day
Members Public

The Auto Industry's Cloud Awakening

Auto manufacturers are behind the cloud adoption curve but are well-positioned to unlock the future of mobility by building foundational capabilities across six key areas.

The Auto Industry's Cloud Awakening