How to Use FileSystemWatcher in C#

FileSystemWatcher in C#

FileSystemWatcher is a class in C# that allows developers to monitor file system changes in a specific directory or a set of directories. It provides events that are raised when certain types of changes occur, such as file creations, deletions, modifications, or renames.

FileSystemWatcher facilitates the detection and notification of alterations within a file or directory.

Advantages of FileSystemWatcher in C#

The FileSystemWatcher in C# presents numerous advantages.

  1. Live Monitoring: It allows developers to keep track of file system modifications in real-time, delivering immediate notifications when files or directories are added, removed, altered, or renamed.
  2. Event-Driven Structure: FileSystemWatcher functions on an event-driven architecture, enabling developers to react promptly to file system alterations without the need for continuous polling.
  3. Optimization: Through event-driven programming, FileSystemWatcher effectively informs applications of changes, reducing the necessity for constant system resource usage in comparison to traditional polling techniques.
  4. Tailored Filtering: It offers customizable filtering capabilities, enabling developers to define the types of modifications to monitor and which files or directories to include or exclude from monitoring.
  5. Adaptability: FileSystemWatcher can be applied in various scenarios like log monitoring, data synchronization, automated backup systems, and more, serving as a versatile tool for managing file system events.
  6. Seamless Integration: It smoothly integrates into C# applications, providing a simple API for implementation and allowing developers to easily integrate file system monitoring features into their projects.
  7. Improved Application Responsiveness: By responding to file system changes in real time, applications utilizing FileSystemWatcher can provide enhanced responsiveness and user experience, particularly in situations where prompt actions are required based on file system events.

In essence, FileSystemWatcher in C# enables developers to construct responsive, efficient, and adaptable applications that can dynamically react to file system changes as they happen.

It can be implemented like below.

Step 1. A basic view was developed to assess the influence of FileSystemWatcher, as illustrated below.

<Window x:Class="FileSystemWatcherExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileSystemWatcherExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Grid>
        <StackPanel VerticalAlignment="Center">
            <Button x:Name="StartFileSystemWatcher" Content="Start Watcher" Click="StartFileSystemWatcher_Click"/>
            <Button x:Name="CreateFile" Content="Create File" Click="CreateFile_Click" Margin="0,10,0,0"/>
            <Button x:Name="ModifyFile" Content="Modify File" Click="ModifyFile_Click" Margin="0,10,0,0"/>
        </StackPanel>
    </Grid>
</Window>

Step 2. Code behind the Xaml view.

using System.IO;
using System.Windows;

namespace FileSystemWatcherExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // Define event handlers
        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"File created: {e.Name}");
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"File deleted: {e.Name}");
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            MessageBox.Show($"File changed: {e.Name}");
        }

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            MessageBox.Show($"File renamed: {e.OldName} to {e.Name}");
        }

        private void StartFileSystemWatcher_Click(object sender, RoutedEventArgs e)
        {
            // Create a new FileSystemWatcher instance
            FileSystemWatcher watcher = new FileSystemWatcher
            {
                IncludeSubdirectories = true,
                // Set the path to the directory you want to monitor
                Path = @"D:\FileSystemFolder",
                // Set the file filters (optional)
                Filter = "*.*"
            };

            // Subscribe to the events you're interested in
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Changed += OnChanged;
            watcher.Renamed += OnRenamed;

            // Enable the watcher
            watcher.EnableRaisingEvents = true;

            MessageBox.Show("FileSystemWatcher started");
        }

        private void CreateFile_Click(object sender, RoutedEventArgs e)
        {
            // Path to the directory
            string directoryPath = @"D:\FileSystemFolder";

            // Check if the directory exists
            if (Directory.Exists(directoryPath))
            {
                // Create a file in the directory
                string filePath = System.IO.Path.Combine(directoryPath, "example.txt");
                File.WriteAllText(filePath, "This is a test file.");

                MessageBox.Show("File created successfully.");
            }
            else
            {
                MessageBox.Show("Directory does not exist.");
            }
        }

        private void ModifyFile_Click(object sender, RoutedEventArgs e)
        {
            // Path to the directory
            string directoryPath = @"D:\FileSystemFolder";

            // Check if the directory exists
            if (Directory.Exists(directoryPath))
            {
                // Create or overwrite a file in the directory
                string filePath = Path.Combine(directoryPath, "example.txt");
                File.WriteAllText(filePath, "File has been modified");

                MessageBox.Show("File modified successfully.");
            }
            else
            {
                MessageBox.Show("Directory does not exist.");
            }
        }
    }
}

Step 3. This code snippet demonstrates how to use the FileSystemWatcher class in C# to monitor a directory and its subdirectories for changes in files or directories.

Instantiation and Configuration

  • FileSystemWatcher watcher = new FileSystemWatcher: This line creates a new instance of the FileSystemWatcher class named watcher.
  • { ... }: This block initializes properties of the watcher instance using object initializer syntax.
  • IncludeSubdirectories = true: Sets the IncludeSubdirectories property to true, indicating that changes in subdirectories should also be monitored.
  • Path = @"D:\FileSystemFolder": Sets the Path property to the directory path "D:\FileSystemFolder" that the watcher will monitor.
  • Filter = "*.*": Sets the Filter property to ".": indicating that the watcher should monitor all files (wildcard for any file extension).

Event Subscription

  • watcher.Created += OnCreated: Subscribes the OnCreated method to the Created event of the watcher instance. This method will be called when a new file or directory is created within the monitored directory.
  • watcher.Deleted += OnDeleted: Subscribes the OnDeleted method to the Deleted event. This method will be called when a file or directory is deleted.
  • watcher.Changed += OnChanged: Subscribes the OnChanged method to the Changed event. This method will be called when the content of a file or directory is changed.
  • watcher.Renamed += OnRenamed: Subscribes the OnRenamed method to the Renamed event. This method will be called when a file or directory is renamed.
  • watcher.Changed -= OnChanged: Unsubscribes the OnChanged method from the Changed event. This line removes the event handler previously added to the Changed event.

Enabling the Watcher

watcher.EnableRaisingEvents = true: Enables the watcher to start raising events for file system changes. Once enabled, the watcher will begin monitoring the specified directory and its subdirectories for any changes based on the subscribed events.

Step 5. View of Xaml for testing.

View of XAML

Note. FileSystemWatcher proves invaluable when monitoring changes within a FileDirectory, its subdirectories, and the included files.