FileSystemWatcher.NotifyFilter Propriedade

Definição

Obtém ou define o tipo de alterações a observar.

public:
 property System::IO::NotifyFilters NotifyFilter { System::IO::NotifyFilters get(); void set(System::IO::NotifyFilters value); };
[System.IO.IODescription("FSW_ChangedFilter")]
public System.IO.NotifyFilters NotifyFilter { get; set; }
public System.IO.NotifyFilters NotifyFilter { get; set; }
[<System.IO.IODescription("FSW_ChangedFilter")>]
member this.NotifyFilter : System.IO.NotifyFilters with get, set
member this.NotifyFilter : System.IO.NotifyFilters with get, set
Public Property NotifyFilter As NotifyFilters

Valor de Propriedade

Um dos NotifyFilters valores. O padrão é a combinação bit a bit OR de LastWrite, FileName, e DirectoryName.

Atributos

Exceções

O valor não é uma combinação válida bit a bit NEM dos NotifyFilters valores.

O valor que está a ser definido não é válido.

Exemplos

O exemplo seguinte cria um FileSystemWatcher para observar o diretório especificado em tempo de execução. O componente está configurado para observar alterações no LastWrite tempo LastAccess , criação, eliminação ou renomeação de ficheiros de texto no diretório. Se um ficheiro for alterado, criado ou eliminado, o caminho para o ficheiro é impresso para a consola. Quando um ficheiro é renomeado, os caminhos antigo e novo são impressos na consola.

using System;
using System.IO;

namespace MyNamespace
{
    class MyClassCS
    {
        static void Main()
        {
            using var watcher = new FileSystemWatcher(@"C:\path\to\folder");

            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;

            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;
            watcher.Error += OnError;

            watcher.Filter = "*.txt";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }

        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            Console.WriteLine($"Changed: {e.FullPath}");
        }

        private static void OnCreated(object sender, FileSystemEventArgs e)
        {
            string value = $"Created: {e.FullPath}";
            Console.WriteLine(value);
        }

        private static void OnDeleted(object sender, FileSystemEventArgs e) =>
            Console.WriteLine($"Deleted: {e.FullPath}");

        private static void OnRenamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine($"Renamed:");
            Console.WriteLine($"    Old: {e.OldFullPath}");
            Console.WriteLine($"    New: {e.FullPath}");
        }

        private static void OnError(object sender, ErrorEventArgs e) =>
            PrintException(e.GetException());

        private static void PrintException(Exception? ex)
        {
            if (ex != null)
            {
                Console.WriteLine($"Message: {ex.Message}");
                Console.WriteLine("Stacktrace:");
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine();
                PrintException(ex.InnerException);
            }
        }
    }
}
Imports System.IO

Namespace MyNamespace

    Class MyClassVB

        Shared Sub Main()
            Using watcher = New FileSystemWatcher("C:\path\to\folder")
                watcher.NotifyFilter = NotifyFilters.Attributes Or
                                       NotifyFilters.CreationTime Or
                                       NotifyFilters.DirectoryName Or
                                       NotifyFilters.FileName Or
                                       NotifyFilters.LastAccess Or
                                       NotifyFilters.LastWrite Or
                                       NotifyFilters.Security Or
                                       NotifyFilters.Size

                AddHandler watcher.Changed, AddressOf OnChanged
                AddHandler watcher.Created, AddressOf OnCreated
                AddHandler watcher.Deleted, AddressOf OnDeleted
                AddHandler watcher.Renamed, AddressOf OnRenamed
                AddHandler watcher.Error, AddressOf OnError

                watcher.Filter = "*.txt"
                watcher.IncludeSubdirectories = True
                watcher.EnableRaisingEvents = True

                Console.WriteLine("Press enter to exit.")
                Console.ReadLine()
            End Using
        End Sub

        Private Shared Sub OnChanged(sender As Object, e As FileSystemEventArgs)
            If e.ChangeType <> WatcherChangeTypes.Changed Then
                Return
            End If
            Console.WriteLine($"Changed: {e.FullPath}")
        End Sub

        Private Shared Sub OnCreated(sender As Object, e As FileSystemEventArgs)
            Dim value As String = $"Created: {e.FullPath}"
            Console.WriteLine(value)
        End Sub

        Private Shared Sub OnDeleted(sender As Object, e As FileSystemEventArgs)
            Console.WriteLine($"Deleted: {e.FullPath}")
        End Sub

        Private Shared Sub OnRenamed(sender As Object, e As RenamedEventArgs)
            Console.WriteLine($"Renamed:")
            Console.WriteLine($"    Old: {e.OldFullPath}")
            Console.WriteLine($"    New: {e.FullPath}")
        End Sub

        Private Shared Sub OnError(sender As Object, e As ErrorEventArgs)
            PrintException(e.GetException())
        End Sub

        Private Shared Sub PrintException(ex As Exception)
            If ex IsNot Nothing Then
                Console.WriteLine($"Message: {ex.Message}")
                Console.WriteLine("Stacktrace:")
                Console.WriteLine(ex.StackTrace)
                Console.WriteLine()
                PrintException(ex.InnerException)
            End If
        End Sub

    End Class

End Namespace

Observações

Pode combinar os membros da NotifyFilters enumeração para observar mais do que um tipo de alteração ao mesmo tempo. Por exemplo, pode observar alterações no tamanho de um ficheiro e alterações no LastWrite tempo. Isto gera um evento sempre que há uma alteração no tamanho do ficheiro ou pasta, ou uma alteração na LastWrite hora do ficheiro ou pasta.

Esta é uma forma de filtrar notificações indesejadas. Para mais informações sobre como filtrar notificações indesejadas, consulte , FilterIncludeSubdirectories, e InternalBufferSize propriedades.

Aplica-se a

Ver também