| The C# FileSystemWatcher class is a powerful tool for monitoring changes within a specified directory. It allows you to detect events such as file creation, deletion, renaming, and changes in file content, providing real-time notifications that can trigger custom actions within your application. By setting up filters, you can focus on specific file types or patterns, allowing you to efficiently react to relevant modifications within your file system. Create a new project and add a form to it. Put a button on the form called button1 then add this code. using System.IO;
private void button1_Click(object sender, System.EventArgs e)
{
FileSystemWatcher objFSW = new FileSystemWatcher();
objFSW.Path = "c:";
objFSW.Filter = "*.*";
objFSW.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
//Setup Events
objFSW.Changed = new FileSystemEventHandler(FileChanged);
objFSW.Created = new FileSystemEventHandler(FileCreated);
objFSW.Deleted = new FileSystemEventHandler(FileDeleted);
objFSW.Renamed = new RenamedEventHandler(FileRenamed);
//Start Things up
objFSW.EnableRaisingEvents = true;
}
public static void FileChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Changed.",e.FullPath);
}
public static void FileCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Created.",e.FullPath);
}
public static void FileDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File {0} was Deleted.",e.FullPath);
}
public static void FileRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File {0} was renamed to {1}", e.OldFullPath, e.FullPath);
}
|