Optimize File Monitoring with Custom .Net8.FileSystemWatcher in .NET

In .NET 8, the FileSystemWatcher.cs functionality seems to be malfunctioning. To address this issue, I've developed a custom solution packaged as 'Custom.Net8.FileSystemWatcher'.It offers functionality akin to FileSystemWatcher.

I can guide you on how you might structure such a custom implementation.

Step 1. Set Up Your Project. I have used the WPF project for it.

Step 2. Add a Necessary NuGet Package like the one below.

NuGet PackageĀ 

Step 3. Implement View for handling different requests like below.

<Window x:Class="WpfAppTester.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:WpfAppTester"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Grid>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="50"/>
            </Grid.RowDefinitions>

            <TextBox x:Name="TxtBxDemo" Grid.Row="0" BorderBrush="LightBlue" BorderThickness="4" Margin="5"/>

            <StackPanel Orientation="Horizontal" Grid.Row="1">
                <Button x:Name="BtnFileCreated" FontSize="15" Content="File Created" Width="200" Click="BtnFileCreated_Click" Margin="5"/>
                <Button x:Name="BtnFileModified" FontSize="15" Content="File Modified" Width="200" Click="BtnFileModified_Click" Margin="5"/>
                <Button x:Name="BtnFileDeleted" FontSize="15" Content="File Deleted" Width="200" Click="BtnFileDeleted_Click" Margin="5"/>
                <Button x:Name="BtnFileRenamed" FontSize="15" Content="File Renamed" Width="200" Click="BtnFileRenamed_Click" Margin="5"/>
            </StackPanel>
        </Grid>
    </Grid>

</Window>

Window

Step 4. Implement CustomFileSystemWatcher like below

using Custom.Net8.FileSystemWatcher;
using System.IO;
using System.Text;
using System.Windows;

namespace WpfAppTester
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        CustomFileSystemWatcher FileSystemWatcher { get; set; }
        
        public MainWindow()
        {
            InitializeComponent();
            FileSystemWatcher = new CustomFileSystemWatcher()
            {
                // This field is required when the user requires notifications from the file system for any changes that occur.
                EnableRaisingEvents = true,

                // When the user wishes to monitor changes not only in the root folder but also in its subfolders.
                // If this feature is disabled, changes that occur in the subfolders will not be monitored.
                IncludeSubdirectories = true,

                // Substitute it with the root directory path of your choice.
                Path = @"C:\Users\sanjay\Desktop\FileGallary",

                // This field must be enabled if the user intends to initiate and monitor changes in a file system.
                FileWatcherStarted = true,

                // The use of the combination of "FileFilter" and "ExtensionType" is solely intended for situations where the user explicitly wishes to inspect changes within a single file.
                // FileFilter = "DemoFile",
                // ExtensionType = ".txt",

                // If the user wishes to exclusively search for files with any extension type.
                // FileFilter = "*.txt",

                // If the user wants to search for a file of any type with any extension.
                FileFilter = "*.*",
            };

            FileSystemWatcher.FileCreated += FileSystemWatcher_FileCreated;
            FileSystemWatcher.FileDeleted += FileSystemWatcher_FileDeleted;
            FileSystemWatcher.FileModified += FileSystemWatcher_FileModified;
            FileSystemWatcher.FileRenamed += FileSystemWatcher_FileRenamed;
        }

        private void FileSystemWatcher_FileRenamed(object? sender, Custom.Net8.FileSystemWatcher.Utilities.CustomRenamedEventArgs e)
        {
            MessageBox.Show("File Renamed");
        }

        private void FileSystemWatcher_FileModified(object? sender, Custom.Net8.FileSystemWatcher.Utilities.CustomFileSystemEventArgs e)
        {
            MessageBox.Show("File Modified");
        }

        private void FileSystemWatcher_FileDeleted(object? sender, Custom.Net8.FileSystemWatcher.Utilities.CustomFileSystemEventArgs e)
        {
            MessageBox.Show("File Deleted");
        }

        private void FileSystemWatcher_FileCreated(object? sender, Custom.Net8.FileSystemWatcher.Utilities.CustomFileSystemEventArgs e)
        {
            MessageBox.Show("File Created");
        }

        private void BtnFileCreated_Click(object sender, RoutedEventArgs e)
        {
            // Check if the file already exists
            if (!File.Exists(System.IO.Path.Combine(@"C:\Users\sanjay\Desktop\FileGallary", "DemoFile.txt")))
            {
                // Create the file and write some content
                using (FileStream fs = File.Create(System.IO.Path.Combine(@"C:\Users\sanjay\Desktop\FileGallary", "DemoFile.txt")))
                {
                    // Write content to the file
                    string content = TxtBxDemo.Text;
                    byte[] bytes = Encoding.UTF8.GetBytes(content);
                    fs.Write(bytes, 0, bytes.Length);
                }
            }
            else
            {
                MessageBox.Show("File already exists.");
            }
        }

        private void BtnFileModified_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(System.IO.Path.Combine(@"C:\Users\sanjay\Desktop\FileGallary", "DemoFile.txt")))
            {
                File.WriteAllText(System.IO.Path.Combine(@"C:\Users\sanjay\Desktop\FileGallary", "DemoFile.txt"), TxtBxDemo.Text);
            }
            else
            {
                MessageBox.Show("File does not exist.");
            }
        }

        private void BtnFileDeleted_Click(object sender, RoutedEventArgs e)
        {
            File.Delete(System.IO.Path.Combine(@"C:\Users\sanjay\Desktop\FileGallary", "DemoFile.txt"));
        }

        private void BtnFileRenamed_Click(object sender, RoutedEventArgs e)
        {
            // Specify the current file path and the new file path
            string currentFilePath = @"C:\Users\sanjay\Desktop\FileGallary\DemoFile.txt";
            string newFilePath = @"C:\Users\sanjay\Desktop\FileGallary\Renamedfilename.txt";
            
            try
            {
                // Create a FileInfo 
                System.IO.FileInfo fi = new System.IO.FileInfo(currentFilePath);
                
                // Check if file is there 
                if (fi.Exists)
                {
                    // Move file with a new name. Hence renamed. 
                    fi.MoveTo(newFilePath);
                    Console.WriteLine("File Renamed.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

Step 5. Result of some actions

The action has resulted in the creation of a file.

File Created

The action has resulted in the modification of a file.

 Modifiaction

The action has resulted in the renaming of a file.

Action

Notes. Implement additional logic as needed inside the event handlers of the CustomWatcher implementation.

Repository Path: https://github.com/OmatrixTech/WpfAppTester


Similar Articles