Using FileSystemWatcher



Click here for a larger image.

Environment: VS7, C#, .NET

This program shows a very interesting .NET class, FileSystemWatcher. It enables you to monitor the file system for changes. A single file, a directory, even all files can be monitored. Basically, you create the class; then, you set the NotifyFilter, the starting path, the file name Filter, and event handlers for the events you want to monitor. Finally, you enable events. The event types are: changed, created, deleted, and renamed. The types of changes include changes to size, attributes, security settings, last write, and last access time. The file name Filter allows you to specify all files "", a particular file "myfile.doc", or use wild cards like "*.txt".

StartingDirectory is obvious. The only other parameter is a Boolean IncludeSubdirectories, also obvious. There are three types of event handlers, FileSystemEventHandler, RenamedEventHandler, and ErrorEventHandler.

// TODO: Add any constructor code after InitializeComponent call

m_starting_path.Text = "C:\\
watcher = new FileSystemWatcher();

//---------------------------------------------------------------

// This routine fills in the FileWatcher instance with parameters.
// It checks the CheckBoxes to see what files to report on and
// what routines to use to handle the events. Then it enables
// raising events, allowing file change notification.

private void StartButtonClick(object sender, System.EventArgs e)
{
  if (watcher.EnableRaisingEvents == true) {
      MessageBeep(100);
      return
  }

m_file_list.Items.Clear();
watcher.Path         = m_starting_path.Text;
watcher.Filter       = m_filter.Text;
watcher.NotifyFilter = NotifyFilters.FileName |
                       NotifyFilters.Attributes |
                       NotifyFilters.LastAccess |
                       NotifyFilters.LastWrite |
                       NotifyFilters.Security |
                       NotifyFilters.Size;

if  (cb_changed.Checked == true)
  watcher.Changed += new FileSystemEventHandler(OnFileEvent);
else watcher.Changed -= new FileSystemEventHandler(OnFileEvent);
if (cb_created.Checked == true)
  watcher.Created += new FileSystemEventHandler(OnFileEvent);
else watcher.Created -= new FileSystemEventHandler(OnFileEvent);
if (cb_deleted.Checked == true)
  watcher.Deleted += new FileSystemEventHandler(OnFileEvent);
else watcher.Deleted -= new FileSystemEventHandler(OnFileEvent);
if (cb_renamed.Checked == true)
  watcher.Renamed += new RenamedEventHandler(OnRenameEvent);
else watcher.Renamed -= new RenamedEventHandler(OnRenameEvent);
if (cb_subdirectory.Checked == true)
  watcher.IncludeSubdirectories = true;
else watcher.IncludeSubdirectories = false;
  watcher.EnableRaisingEvents = true;    //trigger event logging
}

//---------------------------------------------------------------

public void OnFileEvent(object source, FileSystemEventArgs fsea)
{
DateTime dt = new DateTime();
  dt = System.DateTime.UtcNow;
  m_file_list.Items.Add(dt.ToLocalTime() + " " +
                        fsea.ChangeType.ToString() + " " +
                        fsea.FullPath );
}

//---------------------------------------------------------------

public void OnRenameEvent(Object source, RenamedEventArgs rea)
{
DateTime dt = new DateTime();
  dt = System.DateTime.UtcNow;
  m_file_list.Items.Add(dt.ToLocalTime() + " " +
                        rea.ChangeType.ToString() +
                        rea.OldFullPath+ " to " +" " +
                        rea.FullPath);
}

//---------------------------------------------------------------

Downloads

Download demo project - 27 Kb


Comments

  • Problem with code

    Posted by monoplayer on 08/17/2006 12:47pm

    Cross-thread operation not valid: Control 'm_file_list' accessed from a thread other than the thread it was created on. m_file_list.Items.Add(dt.ToLocalTime() + " " + fsea.ChangeType.ToString() + " " + fsea.FullPath );

    • Re: Problem with code

      Posted by icehouse719 on 08/30/2006 09:44am

      one solution - add this to your handler: CheckForIllegalCrossThreadCalls = false;

      Reply
    Reply
  • FileSystemWatcher in WebApplication

    Posted by Legacy on 10/20/2003 12:00am

    Originally posted by: Al

    Does anyone know how to use this FileSystemWatcher in a WebApplication? Would i put it in the Global.asax page?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: October 29, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this eSeminar, Gene Kim will discuss these survey findings and will share woeful tales of artifact management gone wrong! Gene will also share examples of how …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds