Learn To Use FileSystemWatcher in .NET 9

.NET

File System Watcher helps you to monitor file changes on a disk or local network drive.

It can be used on console apps that react to changes according to the files copied, deleted, changed, or created.

I prepared a sample monitoring the OneDrive default user folder to observe PDF files.

Create a console app using

dotnet new console --name myConsoleApp

Add the code below to Program.cs, and you will start monitoring the OneDrive folder on Windows machines.

using System;
using System.IO;
using System.Threading;

class Program
{
    static void Main()
    {
        var fw = new FileSystemWatcher
        {
            Filter = "*.pdf",
            Path = Environment.GetEnvironmentVariable("OneDrive") ?? "C:\\",
            IncludeSubdirectories = true,
            EnableRaisingEvents = true
        };

        fw.Changed += MonikerChange;
        fw.Created += MonikerCreated;

        while (true)
        {
            Thread.Sleep(1000);
        }
    }

    static void MonikerChange(object sender, FileSystemEventArgs e)
    {
        // Handle the file change event
        Console.WriteLine($"File changed: {e.FullPath}");
    }

    static void MonikerCreated(object sender, FileSystemEventArgs e)
    {
        // Handle the file created event
        Console.WriteLine($"File created: {e.FullPath}");
    }
}

Inside the events, you can do whatever you need with the files.

static void MonikerCreated(object sender, FileSystemEventArgs e)
{
    // Handle the file created event
    Console.WriteLine($"File created: {e.FullPath}");
}

To prevent the app from starting more than once, create a Mutex to prevent several instances from running at the same time. You need to create a unique name for your application, replacing UniqueApplicationName.

using (var mutex = new Mutex(true, "UniqueApplicationName", out bool createdNew))
{
    if (!createdNew)
    {
        // Application is already running
        return;
    }

    var fw = new FileSystemWatcher
    {
        Filter = "*.pdf",
        Path = Environment.GetEnvironmentVariable("OneDrive") ?? "C:\\",
        IncludeSubdirectories = true,
        EnableRaisingEvents = true
    };

    fw.Changed += MonikerChange;
    fw.Created += MonikerCreated;

    while (true)
    {
        Thread.Sleep(1000);
    }

    static void MonikerChange(object sender, FileSystemEventArgs e)
    {
        // Handle the file change event
        Console.WriteLine($"File changed: {e.FullPath}");
    }

    static void MonikerCreated(object sender, FileSystemEventArgs e)
    {
        // Handle the file created event
        Console.WriteLine($"File created: {e.FullPath}");
    }
}

You can hide the console screen to avoid the use of terminating the application, and add the code below to the top of the Program.cs.

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const bool HIDE = true;

if (HIDE)
{
    var handle = GetConsoleWindow();
    ShowWindow(handle, SW_HIDE);
}

Conclusion

You can create logs or process files that have been modified, created, deleted, or changed; it's up to you and your requirements to monitor file changes on the hard drive.

Use this resource wisely.

The complete documentation is here.


Recommended Free Ebook
Similar Articles