Using FileSystemWatcher

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.



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

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read