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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds