How to monitor a directory in C#

  By Junaid A   Posted on March-25-2023 

In C#, you can use the FileSystemWatcher class to monitor a directory for changes. Here is an example of how to use the FileSystemWatcher class to monitor a directory and handle changes:

 

using System;
using System.IO;

class DirectoryWatcher
{
    static void Main()
    {
        // Set up the FileSystemWatcher object
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Temp";
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
        watcher.Filter = "*.*";

        // Add event handlers for the events you want to monitor
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Start monitoring the directory
        watcher.EnableRaisingEvents = true;

        // Wait for user to quit program
        Console.WriteLine("Press 'q' to quit.");
        while (Console.Read() != 'q') ;
    }

    // Define the event handlers
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Console.WriteLine($"File {e.FullPath} {e.ChangeType}");
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        Console.WriteLine($"File {e.OldFullPath} renamed to {e.FullPath}");
    }
}
 

 

 

In this example, the FileSystemWatcher object is set up to monitor the C:\Temp directory for changes to any file. The NotifyFilter property is set to LastWrite and FileName, which means that the watcher will only notify you if a file is changed or if a new file is created. The Filter property is set to *.* to watch for all files.

The Changed, Created, Deleted, and Renamed events are handled by the event handlers OnChanged and OnRenamed. These event handlers simply print out a message to the console indicating what file was changed and what type of change occurred.

Finally, the EnableRaisingEvents property is set to true to start monitoring the directory. The program waits for the user to press 'q' before exiting.

By  asifjans    25-Mar-2023 Views  33



You may also read following recent Post

Recent Column What are 3 C
160  By
Recent Column what is .net
388  By