The FileSystemWatcher is pretty straight forward to use. Nut you must
rememeber to call Dispose() once you've finished with it
Here's a sample class that wraps it all and implements IDisposable so
you can Dispose if when finished. It monitors subdirectories but you
must be careful if there are lots of little changes as you'll soon get
a buffer overflow.
You might want to use this in a Windows Service so that it's always
running.
using System;
using System.IO;
using System.Diagnostics;
namespace Monitor_File_System
{
public class FileMonitor : IDisposable
{
private readonly FileSystemWatcher watcher;
public FileMonitor(string path)
{
watcher = new FileSystemWatcher(path);
watcher.Filter = "";
// Monitor all changes
watcher.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime | NotifyFilters.DirectoryName |
NotifyFilters.FileName | NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
// watch subdirecoties but be careful when there could be lots of
changes see InternalBufferSize property
watcher.IncludeSubdirectories = true;
// Watch for all changes
watcher.WaitForChanged(WatcherChangeTypes.All);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
// Start watching
watcher.EnableRaisingEvents = true;
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
Debug.WriteLine("Changed " + e.FullPath);
}
private void watcher_Created(object sender, FileSystemEventArgs e)
{
Debug.WriteLine("Created " + e.FullPath);
}
private void watcher_Deleted(object sender, FileSystemEventArgs e)
{
Debug.WriteLine("Deleted " + e.FullPath);
}
private void watcher_Renamed(object sender, RenamedEventArgs e)
{
Debug.WriteLine("Renamed " + e.FullPath);
}
#region IDisposable Members
public void Dispose()
{
watcher.Dispose();
}
#endregion
}
}