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

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • On-demand Event Event Date: October 23, 2014 Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this webcast to learn why physical appliances are preferable to virtual backup appliances, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds