FileSystemWatcher.Filter プロパティ

定義

ディレクトリで監視するファイルを決定するために使用するフィルター文字列を取得または設定します。Gets or sets the filter string used to determine what files are monitored in a directory.

public:
 property System::String ^ Filter { System::String ^ get(); void set(System::String ^ value); };
public string Filter { get; set; }
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("FSW_Filter")]
public string Filter { get; set; }
[System.IO.IODescription("FSW_Filter")]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string Filter { get; set; }
[System.IO.IODescription("FSW_Filter")]
[System.ComponentModel.SettingsBindable(true)]
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string Filter { get; set; }
[System.ComponentModel.SettingsBindable(true)]
public string Filter { get; set; }
[System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[System.IO.IODescription("File name filter pattern")]
public string Filter { get; set; }
member this.Filter : 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_Filter")>]
member this.Filter : string with get, set
[<System.IO.IODescription("FSW_Filter")>]
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
member this.Filter : string with get, set
[<System.IO.IODescription("FSW_Filter")>]
[<System.ComponentModel.SettingsBindable(true)>]
[<System.ComponentModel.TypeConverter("System.Diagnostics.Design.StringValueConverter, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")>]
member this.Filter : string with get, set
[<System.ComponentModel.SettingsBindable(true)>]
member this.Filter : 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("File name filter pattern")>]
member this.Filter : string with get, set
Public Property Filter As String

プロパティ値

String

フィルター文字列。The filter string. 既定値は " * *" です。(すべてのファイルを監視します。)The default is "*.*" (Watches all files.)

属性

次の例では、を作成して、 FileSystemWatcher 実行時に指定されたディレクトリを監視します。The following example creates a FileSystemWatcher to watch the directory specified at run time. コンポーネントは、 LastWrite LastAccess ディレクトリ内のテキストファイルの変更、作成、削除、または名前変更を監視するように設定されています。The component is set to watch for changes in LastWrite and LastAccess time, the creation, deletion, or renaming of text files in the directory. ファイルが変更、作成、または削除された場合、ファイルへのパスがコンソールに出力されます。If a file is changed, created, or deleted, the path to the file prints to the console. ファイルの名前を変更すると、古いパスと新しいパスがコンソールに出力されます。When a file is renamed, the old and new paths print to the console.

#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

注釈

すべてのファイルの変更を監視するには、 Filter プロパティを空の文字列 ("") に設定します。To watch changes in all files, set the Filter property to an empty string (""). 特定のファイルを監視するには、 Filter プロパティをファイル名に設定します。To watch a specific file, set the Filter property to the file name. たとえば、ファイル MyDoc.txt の変更を監視するには、プロパティを Filter "MyDoc.txt" に設定します。For example, to watch for changes in the file MyDoc.txt, set the Filter property to "MyDoc.txt". また、特定の種類のファイルの変更を監視することもできます。You can also watch for changes in a certain type of file. たとえば、テキストファイルの変更を監視するには、プロパティを Filter "* .txt" に設定します。For example, to watch for changes in any text files, set the Filter property to "*.txt". ".Txt|.doc" などの複数のフィルターの使用はサポートされて * * いません。Use of multiple filters such as "*.txt|*.doc" is not supported.

Filterプロパティは、オブジェクトがイベントの受信を開始した後に変更でき FileSystemWatcher ます。The Filter property can be changed after the FileSystemWatcher object has started receiving events.

不要な通知を除外する方法の詳細については、「」、「」、および「」プロパティを参照してください NotifyFilter IncludeSubdirectories InternalBufferSizeFor more information about filtering out unwanted notifications, see the NotifyFilter, IncludeSubdirectories, and InternalBufferSize properties.

Filter では、次の例に示すように、一致するファイルに対してワイルドカードを使用できます。Filter accepts wildcards for matching files, as shown in the following examples.

フィルター文字列Filter string 次のファイルを監視しますWatches the following files
*.**.* すべてのファイル (既定)。All files (default). 空の文字列 ("") もすべてのファイルを監視します。An empty string ("") also watches all files.
*.txt*.txt "Txt" 拡張子を持つすべてのファイル。All files with a "txt" extension.
* recipe.doc*recipe.doc "レシピ" で終わるすべてのファイルを "doc" 拡張機能と共に使用します。All files ending in "recipe" with a "doc" extension.
win* .xmlwin*.xml "Xml" 拡張機能を持つ "win" で始まるすべてのファイル。All files beginning with "win" with an "xml" extension.
売上 * 200?。xlsSales*200?.xls 次のものと一致します。Matches the following:

-Sales 7 月 2001.xls- Sales July 2001.xls
-売上 2002.xls 8 月- Sales Aug 2002.xls
-Sales 3 月 2004.xls- Sales March 2004.xls

が一致しません。but does not match:

-11 月の売上 1999.xls- Sales Nov 1999.xls
MyReport.DocMyReport.Doc 監視のみ MyReport.docWatches only MyReport.doc

適用対象

こちらもご覧ください