Please navigate to the bottom of the page for Table of Contents

Friday, May 27, 2011

How to monitor file system changes using FileSystemWatcher in C#

Many times your code has to monitor changes made to the file system for new or modified files in order to perform certain operations. For example, you may have a notification service that monitors a particular folder for new images added to that directory. Another way to put this question can be: How can you notify users (subscribers) when a particular txt file has been updated in a particular directory?

.NET provides a FileSystemWatcher object defined in the System.IO namespace. let’s review a function that will enable you to monitor a directory for changes.

using System;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// enable watching
DirectoryWatcher(@"C:\Windows");

// again, stupid code to just keep the function alive
while (true) { Thread.Sleep(1000); }
}


public static void DirectoryWatcher(string directoryToWatch)
{
// check incoming arguments
if (string.IsNullOrWhiteSpace(directoryToWatch))
throw new ArgumentNullException("directoryToWatch");

// create a new FileSystemWatcher
FileSystemWatcher w = new FileSystemWatcher();

// set the directory to watch
w.Path = directoryToWatch;

//this is the heart - setup multiple filters
// to watch various types of changes to watch
w.NotifyFilter = NotifyFilters.Size |
NotifyFilters.FileName |
NotifyFilters.DirectoryName |
NotifyFilters.CreationTime;

// setup which file types do we want to monitor
w.Filter = "*.*";

// setup event handlers to watch for changes
w.Changed += watcher_Change;
w.Created += watcher_Change;
w.Deleted += watcher_Change;
w.Renamed += new RenamedEventHandler(watcher_Renamed);

// just some debugging
Console.WriteLine(
"Manipulate files in {0} to see activity...", directoryToWatch);

// enable watching by allowing events to be raised
w.EnableRaisingEvents = true;
}

static void watcher_Change(object sender,
FileSystemEventArgs e)
{
Console.WriteLine("{0} changed ({1})", e.Name, e.ChangeType);
}
static void watcher_Renamed(object sender,
RenamedEventArgs e)
{
Console.WriteLine("{0} renamed to {1}", e.OldName, e.Name);
}
}
}


This is a very basic example on how to use the file system watcher. The key elements you should note and read more about are the NotifyFilter, Filter and the different notification events (Changed, Created, Deleted, Renamed, etc.).

3 comments:

  1. A couple of questions.
    What drives the FileSystemWatcher? Is it the local machine or can a domain also use this?

    Does it work on a local directory only or does it also work across a network? Will my program running locally be able to detect changes across and network?

    Thanks
    -adam

    ReplyDelete
  2. Yes, a FileSystemWatcher can be used to watch files on a local computer, a network drive or a remote computer. Of course, the account running the program needs to have access to the remote systems.

    ReplyDelete