The FileSystemWatcher class lets you monitor a directory and subdirectories for activity.
FileSystemWatcher has events that fire when files or subdirectories are created, modified, renamed, and deleted, as well as when their attributes change.
using System;
using System.IO;
using System.Linq;
using System.Text;
class Program
{
static void Main() { Watch(@"c:\temp", "*.txt", true); }
static void Watch(string path, string filter, bool includeSubDirs)
{
using (var watcher = new FileSystemWatcher(path, filter))
{
watcher.Created += FileCreatedChangedDeleted;
watcher.Changed += FileCreatedChangedDeleted;
watcher.Deleted += FileCreatedChangedDeleted;
watcher.Renamed += FileRenamed;
watcher.Error += FileError;
watcher.IncludeSubdirectories = includeSubDirs;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Listening for events - press to end");
Console.ReadLine();
}
}
static void FileCreatedChangedDeleted(object o, FileSystemEventArgs e)
{
Console.WriteLine("File {0} has been {1}", e.FullPath, e.ChangeType);
}
static void FileRenamed(object o, RenamedEventArgs e)
{
Console.WriteLine("Renamed: {0}->{1}", e.OldFullPath, e.FullPath);
}
static void FileError(object o, ErrorEventArgs e)
{
Console.WriteLine("Error: " + e.GetException().Message);
}
}