Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Create and Use FileSystemWatcher in Windows

FileSystemWatcher is a powerful .NET class that allows developers to monitor changes to the file system. This can be particularly useful for applications that need to respond to changes in real-time, such as file synchronization tools, log monitoring systems, or automated backup solutions. In the Windows environment, FileSystemWatcher is fully supported and can be implemented using C# in a .NET application. This article will guide you through the process of creating and using FileSystemWatcher in a Windows environment, providing practical examples and sample code.


Examples:


Example 1: Setting Up FileSystemWatcher in a C# Console Application


1. Create a new C# Console Application:



  • Open Visual Studio.

  • Create a new project and select "Console App (.NET Core)".

  • Name your project and click "Create".


2. Add FileSystemWatcher Code:




  • Open the Program.cs file and replace its content with the following code:


    using System;
    using System.IO;

    namespace FileSystemWatcherExample
    {
    class Program
    {
    static void Main(string[] args)
    {
    using (FileSystemWatcher watcher = new FileSystemWatcher())
    {
    watcher.Path = @"C:\Path\To\Directory"; // Set the directory to watch

    // Watch for changes in LastWrite times, and the renaming of files or directories.
    watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    // Only watch text files.
    watcher.Filter = "*.txt";

    // Add event handlers.
    watcher.Changed += OnChanged;
    watcher.Created += OnChanged;
    watcher.Deleted += OnChanged;
    watcher.Renamed += OnRenamed;

    // Begin watching.
    watcher.EnableRaisingEvents = true;

    // Wait for the user to quit the program.
    Console.WriteLine("Press 'q' to quit the sample.");
    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}");
    }
    }



3. Run the Application:



  • Build and run the application.

  • The console will display messages when changes are detected in the specified directory.


Example 2: Running FileSystemWatcher via PowerShell


1. Open PowerShell:



  • Press Win + X and select "Windows PowerShell (Admin)".


2. Create a PowerShell Script:




  • Open a text editor and paste the following script:


    $path = "C:\Path\To\Directory"
    $filter = "*.txt"

    $FileSystemWatcher = New-Object System.IO.FileSystemWatcher
    $FileSystemWatcher.Path = $path
    $FileSystemWatcher.Filter = $filter
    $FileSystemWatcher.IncludeSubdirectories = $true
    $FileSystemWatcher.EnableRaisingEvents = $true

    $onChange = Register-ObjectEvent $FileSystemWatcher Changed -SourceIdentifier FileChanged -Action {
    Write-Host "File $($Event.SourceEventArgs.FullPath) has been changed"
    }

    $onCreate = Register-ObjectEvent $FileSystemWatcher Created -SourceIdentifier FileCreated -Action {
    Write-Host "File $($Event.SourceEventArgs.FullPath) has been created"
    }

    $onDelete = Register-ObjectEvent $FileSystemWatcher Deleted -SourceIdentifier FileDeleted -Action {
    Write-Host "File $($Event.SourceEventArgs.FullPath) has been deleted"
    }

    $onRename = Register-ObjectEvent $FileSystemWatcher Renamed -SourceIdentifier FileRenamed -Action {
    Write-Host "File $($Event.SourceEventArgs.OldFullPath) has been renamed to $($Event.SourceEventArgs.FullPath)"
    }

    Write-Host "Monitoring changes to $path. Press Enter to exit."
    [System.Console]::ReadLine() | Out-Null

    Unregister-Event -SourceIdentifier FileChanged
    Unregister-Event -SourceIdentifier FileCreated
    Unregister-Event -SourceIdentifier FileDeleted
    Unregister-Event -SourceIdentifier FileRenamed



3. Save and Run the Script:



  • Save the script as FileSystemWatcher.ps1.

  • Run the script in PowerShell by navigating to its directory and executing:
     .\FileSystemWatcher.ps1


To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.