FileSystemWatcher.Path 속성

정의

조사할 디렉터리의 경로를 가져오거나 설정합니다.

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

속성 값

String

모니터링할 경로입니다. 기본값은 빈 문자열("")입니다.

특성

예외

지정된 경로가 없거나 찾지 못한 경우

또는

지정된 경로에 와일드카드 문자가 포함되어 있는 경우

또는

지정된 경로에 잘못된 경로 문자가 포함되어 있는 경우

예제

다음 예제에서는 런타임에 지정된 디렉터리를 감시하는 방법을 만듭니다 FileSystemWatcher . 구성 요소는 디렉터리에서 LastWrite LastAccess 텍스트 파일의 변경 내용, 생성, 삭제 또는 이름 바꾸기를 감시하도록 설정됩니다. 파일이 변경, 생성 또는 삭제되면 파일 경로가 콘솔에 출력됩니다. 파일 이름을 바꾸면 이전 경로와 새 경로가 콘솔에 출력됩니다.

#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

설명

디렉터리에 대한 정규화된 경로입니다. 속성이 IncludeSubdirectories true면 이 디렉터리가 시스템에서 변경 내용을 감시하는 루트이고, 그렇지 않으면 감시된 유일한 디렉터리입니다. 특정 파일을 보려면 속성을 정규화된 올바른 디렉터리로 Filter 설정하고 속성을 파일 이름으로 설정합니다Path.

이 속성은 Path UNC(유니버설 명명 규칙) 경로를 지원합니다.

참고

구성 요소가 변경 내용을 감시하려면 먼저 이 속성을 설정해야 합니다.

디렉터리의 이름이 바뀌면 FileSystemWatcher 새로 이름이 바뀐 항목에 자동으로 다시 연결됩니다. 예를 들어 속성을 "C:\My Documents"로 설정한 Path 다음 디렉터리의 이름을 수동으로 "C:\Your Documents"로 바꾸면 구성 요소는 새로 이름이 바뀐 디렉터리에서 변경 알림을 계속 수신 대기합니다. 그러나 속성을 요청 Path 하면 이전 경로가 포함됩니다. 이는 구성 요소가 디렉터리의 이름이 아닌 핸들을 기준으로 감시하는 디렉터리를 결정하기 때문에 발생합니다. 이름 바꾸기는 핸들에 영향을 주지 않습니다. 따라서 구성 요소를 삭제 하 고 다음 업데이트 하지 않고 다시 작성 하는 경우는 Path 속성을 애플리케이션 디렉터리를 더 이상 존재 하기 때문에 실패 합니다.

적용 대상

추가 정보