FileSystemWatcher.Path Właściwość

Definicja

Pobiera lub ustawia ścieżkę katalogu do obejrzenia.

public:
 property System::String ^ Path { System::String ^ get(); void set(System::String ^ value); };
public string Path { get; set; }
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("FSW_Path")]
public string Path { get; set; }
[System.IO.IODescription("FSW_Path")]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string Path { get; set; }
[System.IO.IODescription("FSW_Path")]
[System.ComponentModel.SettingsBindable(true)]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string Path { get; set; }
[System.ComponentModel.SettingsBindable(true)]
public string Path { get; set; }
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("The directory to monitor")]
public string Path { get; set; }
member this.Path : string with get, set
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
[<System.IO.IODescription("FSW_Path")>]
member this.Path : string with get, set
[<System.IO.IODescription("FSW_Path")>]
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
member this.Path : string with get, set
[<System.IO.IODescription("FSW_Path")>]
[<System.ComponentModel.SettingsBindable(true)>]
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
member this.Path : string with get, set
[<System.ComponentModel.SettingsBindable(true)>]
member this.Path : string with get, set
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
[<System.IO.IODescription("The directory to monitor")>]
member this.Path : string with get, set
Public Property Path As String

Wartość właściwości

String

Ścieżka do monitorowania. Wartością domyślną jest ciąg pusty ("").

Atrybuty

Wyjątki

Określona ścieżka nie istnieje lub nie można jej odnaleźć.

-lub-

Określona ścieżka zawiera symbole wieloznaczne.

-lub-

Określona ścieżka zawiera nieprawidłowe znaki ścieżki.

Przykłady

Poniższy przykład tworzy obiekt w FileSystemWatcher celu obejrzenia katalogu określonego w czasie wykonywania. Składnik jest ustawiony, aby obserwować zmiany w czasie LastWrite i LastAccess , tworzenie, usuwanie lub zmienianie nazw plików tekstowych w katalogu. Jeśli plik zostanie zmieniony, utworzony lub usunięty, ścieżka do pliku zostanie wyświetlona w konsoli programu . Po zmianie nazwy pliku stare i nowe ścieżki są drukowane w konsoli programu .

#include "pch.h"

using namespace System;
using namespace System::IO;

class MyClassCPP
{
public:

    int static Run()
    {
        FileSystemWatcher^ watcher = gcnew FileSystemWatcher("C:\\path\\to\\folder");

        watcher->NotifyFilter = static_cast<NotifyFilters>(NotifyFilters::Attributes
                                                         | NotifyFilters::CreationTime
                                                         | NotifyFilters::DirectoryName
                                                         | NotifyFilters::FileName
                                                         | NotifyFilters::LastAccess
                                                         | NotifyFilters::LastWrite
                                                         | NotifyFilters::Security
                                                         | NotifyFilters::Size);

        watcher->Changed += gcnew FileSystemEventHandler(MyClassCPP::OnChanged);
        watcher->Created += gcnew FileSystemEventHandler(MyClassCPP::OnCreated);
        watcher->Deleted += gcnew FileSystemEventHandler(MyClassCPP::OnDeleted);
        watcher->Renamed += gcnew RenamedEventHandler(MyClassCPP::OnRenamed);
        watcher->Error   += gcnew ErrorEventHandler(MyClassCPP::OnError);

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

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

        return 0;
    }

private:

    static void OnChanged(Object^ sender, FileSystemEventArgs^ e)
    {
        if (e->ChangeType != WatcherChangeTypes::Changed)
        {
            return;
        }
        Console::WriteLine("Changed: {0}", e->FullPath);
    }

    static void OnCreated(Object^ sender, FileSystemEventArgs^ e)
    {
        Console::WriteLine("Created: {0}", e->FullPath);
    }

    static void OnDeleted(Object^ sender, FileSystemEventArgs^ e)
    {
        Console::WriteLine("Deleted: {0}", e->FullPath);
    }

    static void OnRenamed(Object^ sender, RenamedEventArgs^ e)
    {
        Console::WriteLine("Renamed:");
        Console::WriteLine("    Old: {0}", e->OldFullPath);
        Console::WriteLine("    New: {0}", e->FullPath);
    }

    static void OnError(Object^ sender, ErrorEventArgs^ e)
    {
        PrintException(e->GetException());
    }

    static void PrintException(Exception^ ex)
    {
        if (ex != nullptr)
        {
            Console::WriteLine("Message: {0}", ex->Message);
            Console::WriteLine("Stacktrace:");
            Console::WriteLine(ex->StackTrace);
            Console::WriteLine();
            PrintException(ex->InnerException);
        }
    }
};


int main()
{
    MyClassCPP::Run();
}
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

Uwagi

Jest to w pełni kwalifikowana ścieżka do katalogu. IncludeSubdirectories Jeśli właściwość to true, ten katalog jest katalogiem głównym, w którym system obserwuje zmiany. W przeciwnym razie jest to jedyny katalog obserwowany. Aby obejrzeć określony plik, ustaw Path właściwość na w pełni kwalifikowany, poprawny katalog i Filter właściwość na nazwę pliku.

Właściwość Path obsługuje ścieżki Universal Naming Convention (UNC).

Uwaga

Tę właściwość należy ustawić, zanim składnik będzie mógł obserwować zmiany.

Po zmianie nazwy FileSystemWatcher katalogu automatycznie dołącza się do nowo zmienionego elementu. Jeśli na przykład właściwość zostanie ustawiona Path na "C:\Moje dokumenty", a następnie ręcznie zmień nazwę katalogu na "C:\Your Documents", składnik kontynuuje nasłuchiwanie powiadomień o zmianach w nowo zmienionym katalogu. Jednak po wyświetleniu zapytania o Path właściwość zawiera starą ścieżkę. Dzieje się tak, ponieważ składnik określa, które katalogi są oglądane na podstawie uchwytu, a nie nazwy katalogu. Zmiana nazwy nie ma wpływu na uchwyt. Jeśli więc zniszczysz składnik, a następnie ponownie utworzysz go bez aktualizacji Path właściwości, aplikacja zakończy się niepowodzeniem, ponieważ katalog już nie istnieje.

Dotyczy

Zobacz też