How to monitor a directory in C#

In this article, we will discuss how to monitor a directory in C#. Monitoring changes in a folder is an essential aspect of many applications, as it allows the application to respond to changes made to files within the folder. In .NET, there are several ways to monitor changes in a folder, including using the FileSystemWatcher class, polling the directory for changes, or using third-party libraries. In this article, we will explore these approaches and provide examples of how to implement them. In .NET, monitoring changes in a folder can be achieved using the FileSystemWatcher class. The FileSystemWatcher class can be used to monitor changes in a specified directory and its subdirectories, including file and folder creations, deletions, modifications, and renames. This class can be used in various scenarios, such as tracking changes to configuration files, monitoring log files, and detecting changes to user-generated content.



What is a File System and What are File System Changes? :


An operating system's file system specifies how it arranges the files and folders on a disc. In other words, it symbolizes the fundamental organization that an operating system employs to store, control, and maintain a record of information on a storage medium like a hard disc. Each file system has a distinct method for classifying files as well as unique features and capabilities. There are numerous file systems, including FAT, NTFS, Unix, HFS+, etc.

When a file system's state changes, an event called a "file system change" takes place. This may take place during the creation, modification, or deletion of a file or directory. The structure of the file system might also change, for example, when a directory is moved or renamed. For several reasons, it may be important to detect file system modifications. For instance, a developer could wish to keep an eye out for fresh files in a directory and handle them appropriately. Alternatively, you might wish to keep track of configuration file alterations so you can reload it if required.



How to Detect File System Changes in C#:


The FileSystemWatcher class is an excellent way to keep track of what's happening in your file system and make sure your data is constantly tracked. As previously said, you may monitor changes to your file system using this class and take appropriate action. All programmers need to do to detect file system changes in their code is set up a watcher and handle the Modified, Created, and Deleted events. This is made simple by the FileSystemWatcher class in C#. In the sections that follow, we show you how to do this.



Configuring FileSystemWatcher to Watch for Changes :


The FileSystem Watcher class is an excellent way to keep track of what's happening in your file system and make sure your data is constantly current. As previously said, you may monitor changes to your file system using this class and take appropriate action.

All programmers need to do to detect file system changes in their code is set up a watcher and handle the Modified, Created, and Deleted events. This is made simple by the FileSystemWatcher class in C#. In the sections that follow, we show you how to do this.


To use the FileSystemWatcher class in a .NET application, you need to follow these steps:


  • Create a new instance of the FileSystemWatcher class.


  • Set the properties of the FileSystemWatcher class to specify the directory to monitor and the types of changes to track.


  • Add event handlers to respond to the events raised by the FileSystemWatcher class.


  • Start the monitoring process by calling the Start() method of the FileSystemWatcher class.



The following code example shows how to configure FileSystemWatcher in C#:

 

    {

        FileSystemWatcher watcher = new FileSystemWatcher();

        watcher.Path = "C:\\MyFolder";

        watcher.EnableRaisingEvents = true;

        watcher.Filter = "*.txt";

    }




The NotifyFilter property can be used to specify which types of changes you want to be notified about. The available options are:

  • FileName


  • DirectoryName


  • Attributes


  • Size


  • LastWrite


  • LastAccess


  • CreationTime


  • Security



You can select to receive notifications for several file system changes, it should be noted. Use the C# code below, for instance, to get informed when file names and attributes change.


FileSystemWatcher watcher = new FileSystemWatcher();

watcher.Path = @"C:\MyFolder";

watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;

watcher.Filter = "*.*";

watcher.EnableRaisingEvents = true;




Here is an example of using the FileSystemWatcher class in a .NET application:


using System;

using System.IO;

class Program

{

    static void Main(string[] args)

    {

        // Create a new FileSystemWatcher and set its properties

        FileSystemWatcher watcher = new FileSystemWatcher();

        watcher.Path = @"E:\Github\contentBlog\MonitorChanges";

        watcher.IncludeSubdirectories = true;

        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        // Add event handlers for the events raised by the FileSystemWatcher

        watcher.Created += OnFileChanged;

        watcher.Deleted += OnFileChanged;

        watcher.Changed += OnFileChanged;

        watcher.Renamed += OnFileRenamed;

        // Start monitoring the directory

        watcher.EnableRaisingEvents = true;

        // Wait for user input to exit the program

        Console.WriteLine("Press 'q' to quit the program.");

        while (Console.Read() != 'q') ;

    }

    // Event handler for file/folder creations, deletions, and modifications

    static void OnFileChanged(object sender, FileSystemEventArgs e)

    {

        Console.WriteLine($"File/folder {e.FullPath} {e.ChangeType}");

    }

    // Event handler for file/folder renames

    static void OnFileRenamed(object sender, RenamedEventArgs e)

    {

        Console.WriteLine($"File/folder {e.OldFullPath} renamed to {e.FullPath}");

    }

}



Now as you can see the output in the blow screenshot after successfully executing the program according to the above code.

monitor_first.png


Here you can see on the left side we have the folder files directory and on the right hand, we have the console output screen.


FileSystemWatcher class comes in handy when we want to monitor a folder for any changes made. Now just look at the below screenshot where while creating a text file named “New Text Document
so its changes effecting on the console output screen.

monitor_second.png


Now suppose we try to rename the file name “New Text Document” to “ CodetoSolutions” then it’s affecting and showing on the console output screen also its modifications, As you can see in the below screenshot.

monitor_third.png


Let’s suppose we try to delete the file and then just have to look at the below screenshot how It’s affecting the console output screen.

monitor_fourth.png



Working with Events in C#:


We need to instruct the FileSystemWatcher on what to do when a change is discovered now that it has been configured. To accomplish this, we subscribe to an event that the FileSystemWatcher class provides. The Changed event is the most popular one to subscribe to.

The FileSystemWatcher class raises several events, including:


  • Changed: This event is generated when you modify a file or directory in the path being watched.


  • Created:  This event occurs whenever you create a file or directory in the path you would like to monitor.


  • Deleted: This event occurs when a file or directory is deleted from the path you would like to monitor.


  • Error: This event is generated if there is an error in the monitored path.


  • Renamed: Whenever you rename a file or directory within the monitored path, this event will be triggered.


The following line of code demonstrates how to register events in C# using FileSystemWatcher:


// Create a new FileSystemWatcher and set its properties

FileSystemWatcher watcher = new FileSystemWatcher();


watcher
.Path = @"C:\MyFolder";


watcher
.IncludeSubdirectories = true;


watcher
.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;


// Add event handlers for the events raised by the FileSystemWatcher


watcher
.Created += OnFileChanged;


watcher
.Deleted += OnFileChanged;


watcher
.Changed += OnFileChanged;


watcher
.Renamed += OnFileRenamed;


// Start monitoring the directory


watcher
.EnableRaisingEvents = true;



Note: Keep in mind that you need to have the appropriate event handler available for each of the events described here.


Pros of Using the FileSystemWatcher Class in C#:


Pros:

  • Quick to set up and simple to use.


  • The FileSystemWatcher class allows programmers to simultaneously monitor a folder and all of its subfolders.


  • able to keep an eye on both local and remote file systems.



Conclusion:


In a variety of circumstances, the capacity to recognize file system changes can be an extremely useful tool. This C# programming lesson covered how to use the FileSystemWatcher class in C# to allow programmers to monitor file system changes. We also taught how to respond to the events that were raised and how to filter them. With this information, you should be able to modify your apps to include file system change detection as required.

Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee