using System.IO; class Example { static void Main() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = "C:\\MyFolder"; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Changed += OnChanged; watcher.Renamed += OnRenamed; watcher.EnableRaisingEvents = true; // Keep the console window open Console.ReadLine(); } static void OnChanged(object source, FileSystemEventArgs e) { Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); } static void OnRenamed(object source, RenamedEventArgs e) { Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); } }
using System.IO; class Example { static void Main() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = "C:\\MyFolder"; watcher.Filter = "file.txt"; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Changed += OnChanged; watcher.EnableRaisingEvents = true; // Keep the console window open Console.ReadLine(); } static void OnChanged(object source, FileSystemEventArgs e) { string backupPath = "C:\\MyBackupFolder\\" + e.Name; File.Copy(e.FullPath, backupPath, true); Console.WriteLine("Backup created: " + backupPath); } }This example creates a FileSystemWatcher object that monitors a specific file for changes. When the file is changed, the OnChanged event handler method is called. This method creates a backup of the file in a separate directory, and then displays a message indicating that the backup was created. Package library: System.IO.File.Copy