Watching Files Programmatically

FileSystemWatcher class can be quite helpful when you want to monitor (or "watch") files on your system programmatically. Specicifally, you can instruct FileSystemWatcher type to monitor files for any of the actions specified by the System.IO.NotifyFilters enumeration.

public enum NotifyFilters
 {
     Attributes, CreationTime,
     DirectoryName, FileName,
     LastAccess, LastWrite,
     Security, Size
 }

You may choose to handle the Changed,Created and Deleted events, all which work in conjunction with the FileSystemEventHandler delegate.

// The FileSystemEventHandler delegate must point to methods matching the following signature.
void MyNotificationHandler(object source, FileSystemEventArgs e);

You can also handle the Renamed event using the RenamedEventHandler delegate type.

// The RenamedEventHandler delegate must point to methods matching the following signature.
void MyRenamedHandler(object source, RenamedEventArgs e);

FileSystemWatcher watcher = new();
try
 {
     watcher.Path = @".";
 }
catch (Exception ex)
 {
     Console.WriteLine(ex.Message);
 }
 
// Set up the things to be on the lookout for.
watcher.NotifyFilter = NotifyFilters.LastAccess |
     NotifyFilters.LastWrite |
     NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
 
// Add event handlers.
// Specify what is done when a file is changed, created, or deleted.
watcher.Changed += (s, e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}!");
watcher.Created += (s, e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}!");
watcher.Deleted += (s, e) =>
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}!");
// Specify what is done when a file is renamed.
watcher.Renamed += (s, e) =>
Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
// Begin watching the directory.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine(@"Press 'q' to quit app.");
// Raise some events.
using (var sw = File.CreateText("Test.txt"))
 {
     sw.Write("This is some text");
 }
File.Move("Test.txt", "Test2.txt");
File.Delete("Test2.txt");
while (Console.Read() != 'q') ;