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

  • The proliferation of cloud computing options has begun to change the way storage is thought about, procured, and used. IT managers and departments need to think through how cloud options might fit into and complement their onsite data infrastructures. This white paper explains cloud storage and backup, providing advice about the tools and best practices for its implementation and use. Read this white paper for some useful takeaways about how to take advantage of cloud storage for high availability, backup and …

  • As everyone scrambles to protect customers and consumers from the Heartbleed virus, there will be a variety of mitigating solutions offered up to address this pesky bug. There are a variety of points within the data path where solutions could be put into place to mitigate this (and similar) vulnerabilities and customers must choose the most strategic point in the network at which to deploy their selected mitigation. Read this white paper to learn the ins and outs of mitigating the risk of Heartbleed and the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds