Discover How to Utilize FileSystemWatcher in ASP.NET 9

Leave a Comment

You can track file changes on a disk or local network device with the aid of File System Watcher. Console applications that respond to modifications based on the files that are copied, erased, altered, or generated can use it.

I set up an example to watch PDF files in the OneDrive default user folder. Make a console application with.

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.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment