C# FileSystemWatcher listens to the file system and places a watch on a directory, its subdirecttories, and files and notifies if any changes are made to the directory. This class is useful when you need to auto update the updates in a directory. For example, if you want to create an auto backup of a folder, you can implement a File system watcher service that watches a directory or entire machine and find when and what changes are made and copy the changes to the backup device.
C# FileSystemWatcher acts as a watchdog for file system changes and raises an event when a change occurs. You must specify a directory to be monitored. The class can monitor changes to subdirectories and files within the specified directory. If you have Windows 2000 or later OS, you can even monitor a remote system for changes. The option to monitor files with specific extensions can be set using the Filter property of the FileSystemWatcher class. You can also fine-tune FileSystemWatcher to monitor any change in file Attributes, LastAccess, LastWrite, Security, and Size data.
The FileSystemWatcher class raises the events described in Table 1.

Table 1. FileSystemaWatcher class events
Here is a complete console application that shows how to use the FileSystemWatcher in C#. The code also implements its events. You can use the same code in a Windows Service to schedule it automatically to watch a directory. The FileSystemWatcher is defined in the System.IO namespace. Make sure to import this namespace before you use the class.
Listing 1. Using the FileSystemWatcher Class using C#
- using System;
- using System.IO;
- public class FileWatcher
- {
- public static void Main(string[] args)
- {
- // If a directory is not specified, exit program.
- if (args.Length != 1)
- {
- // Display the proper way to call the program.
- Console.WriteLine("Usage: FileWatcher.exe <directory>");
- return;
- }
- try
- {
- // Create a new FileSystemWatcher and set its properties.
- FileSystemWatcher watcher = new FileSystemWatcher();
- watcher.Path = args[0];
- // Watch both files and subdirectories.
- watcher.IncludeSubdirectories = true;
- // Watch for all changes specified in the NotifyFilters
- //enumeration.
- watcher.NotifyFilter = NotifyFilters.Attributes |
- NotifyFilters.CreationTime |
- NotifyFilters.DirectoryName |
- NotifyFilters.FileName |
- NotifyFilters.LastAccess |
- NotifyFilters.LastWrite |
- NotifyFilters.Security |
- NotifyFilters.Size;
- // Watch all files.
- watcher.Filter = "*.*";
- // Add event handlers.
- watcher.Changed += new FileSystemEventHandler(OnChanged);
- watcher.Created += new FileSystemEventHandler(OnChanged);
- watcher.Deleted += new FileSystemEventHandler(OnChanged);
- watcher.Renamed += new RenamedEventHandler(OnRenamed);
- //Start monitoring.
- watcher.EnableRaisingEvents = true;
- //Do some changes now to the directory.
- //Create a DirectoryInfo object.
- DirectoryInfo d1 = new DirectoryInfo(args[0]);
- //Create a new subdirectory.
- d1.CreateSubdirectory("mydir");
- //Create some subdirectories.
- d1.CreateSubdirectory("mydir1\\mydir2\\mydir3");
- //Move the subdirectory "mydir3 " to "mydir\mydir3"
- Directory.Move(d1.FullName + "file://mydir1//mydir2//mydir3",
- d1.FullName + "\\mydir\\mydir3");
- //Check if subdirectory "mydir1" exists.
- if (Directory.Exists(d1.FullName + "\\mydir1"))
- {
- //Delete the directory "mydir1"
- //I have also passed 'true' to allow recursive deletion of
- //any subdirectories or files in the directory "mydir1"
- Directory.Delete(d1.FullName + "\\mydir1", true);
- }
- //Get an array of all directories in the given path.
- DirectoryInfo[] d2 = d1.GetDirectories();
- //Iterate over all directories in the d2 array.
- foreach (DirectoryInfo d in d2)
- {
- if (d.Name == "mydir")
- {
- //If "mydir" directory is found then delete it recursively.
- Directory.Delete(d.FullName, true);
- }
- }
- // Wait for user to quit program.
- Console.WriteLine("Press \'q\' to quit the sample.");
- Console.WriteLine();
- //Make an infinite loop till 'q' is pressed.
- while (Console.Read() != 'q') ;
- }
- catch (IOException e)
- {
- Console.WriteLine("A Exception Occurred :" + e);
- }
- catch (Exception oe)
- {
- Console.WriteLine("An Exception Occurred :" + oe);
- }
- }
- // Define the event handlers.
- public static void OnChanged(object source, FileSystemEventArgs e)
- {
- // Specify what is done when a file is changed.
- Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
- }
- public static void OnRenamed(object source, RenamedEventArgs e)
- {
- // Specify what is done when a file is renamed.
- Console.WriteLine(" {0} renamed to {1}", e.OldFullPath, e.FullPath);
- }
- }


Bill HolmanPosted Jan 4, 2022, 10:27 PM
Works perfectly out of the box. Thank you for sharing!