FileSystemWatcher クラス

定義

ファイル システムの変更通知を待機し、ディレクトリまたはディレクトリ内のファイルが変更されたときにイベントを発生させます。

public ref class FileSystemWatcher : System::ComponentModel::Component, System::ComponentModel::ISupportInitialize
public ref class FileSystemWatcher : IDisposable
public class FileSystemWatcher : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
public class FileSystemWatcher : IDisposable
[System.IO.IODescription("FileSystemWatcherDesc")]
public class FileSystemWatcher : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type FileSystemWatcher = class
    inherit Component
    interface ISupportInitialize
type FileSystemWatcher = class
    interface IDisposable
[<System.IO.IODescription("FileSystemWatcherDesc")>]
type FileSystemWatcher = class
    inherit Component
    interface ISupportInitialize
Public Class FileSystemWatcher
Inherits Component
Implements ISupportInitialize
Public Class FileSystemWatcher
Implements IDisposable
継承
FileSystemWatcher
継承
FileSystemWatcher
属性
実装

次の例では、 をFileSystemWatcher作成して、実行時に指定されたディレクトリをwatchします。 コンポーネントは、ディレクトリ内のテキスト ファイルのLastWriteLastAccess変更、作成、削除、または名前変更をwatchに設定されます。 ファイルが変更、作成、または削除されると、ファイルへのパスがコンソールに出力されます。 ファイルの名前が変更されると、古いパスと新しいパスがコンソールに出力されます。

#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

注釈

この API の詳細については、「 FileSystemWatcher の補足 API 解説」を参照してください。

コンストラクター

FileSystemWatcher()

FileSystemWatcher クラスの新しいインスタンスを初期化します。

FileSystemWatcher(String)

監視するディレクトリを指定して、FileSystemWatcher クラスの新しいインスタンスを初期化します。

FileSystemWatcher(String, String)

FileSystemWatcher クラスの新しいインスタンスを、監視するディレクトリとファイルの種類を指定して初期化します。

プロパティ

CanRaiseEvents

コンポーネントがイベントを発生させることがきるかどうかを示す値を取得します。

(継承元 Component)
Container

IContainer を含む Component を取得します。

(継承元 Component)
DesignMode

Component が現在デザイン モードかどうかを示す値を取得します。

(継承元 Component)
EnableRaisingEvents

コンポーネントが有効かどうかを示す値を取得または設定します。

Events

Component に結び付けられているイベント ハンドラーのリストを取得します。

(継承元 Component)
Filter

ディレクトリで監視するファイルを決定するために使用するフィルター文字列を取得または設定します。

Filters

ディレクトリ内で監視するファイルを決定するために、使用されているすべてのフィルターのコレクションを取得します。

IncludeSubdirectories

指定したパスのサブディレクトリを監視するかどうかを示す値を取得または設定します。

InternalBufferSize

内部バッファーのサイズ (バイト単位) を取得または設定します。

NotifyFilter

ウォッチする変更の種類を取得または設定します。

Path

ウォッチするディレクトリのパスを取得または設定します。

Site

ISiteFileSystemWatcher を取得または設定します。

SynchronizingObject

ディレクトリ変更の結果として発行されるイベント ハンドラー呼び出しをマーシャリングするために使用するオブジェクトを取得または設定します。

メソッド

BeginInit()

フォームまたは別のコンポーネントで使用する FileSystemWatcher の初期化を開始します。 初期化は実行時に発生します。

CreateObjRef(Type)

リモート オブジェクトとの通信に使用するプロキシの生成に必要な情報をすべて格納しているオブジェクトを作成します。

(継承元 MarshalByRefObject)
Dispose()

FileSystemWatcher で使用されるアンマネージ リソースを解放します。

Dispose()

Component によって使用されているすべてのリソースを解放します。

(継承元 Component)
Dispose(Boolean)

FileSystemWatcher によって使用されているアンマネージド リソースを解放し、オプションでマネージド リソースも解放します。

EndInit()

フォームまたは別のコンポーネントで使用する FileSystemWatcher の初期化を終了します。 初期化は実行時に発生します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetLifetimeService()
古い.

対象のインスタンスの有効期間ポリシーを制御する、現在の有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
GetService(Type)

Component またはその Container で提供されるサービスを表すオブジェクトを返します。

(継承元 Component)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
InitializeLifetimeService()
古い.

このインスタンスの有効期間ポリシーを制御する有効期間サービス オブジェクトを取得します。

(継承元 MarshalByRefObject)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
MemberwiseClone(Boolean)

現在の MarshalByRefObject オブジェクトの簡易コピーを作成します。

(継承元 MarshalByRefObject)
OnChanged(FileSystemEventArgs)

Changed イベントを発生させます。

OnCreated(FileSystemEventArgs)

Created イベントを発生させます。

OnDeleted(FileSystemEventArgs)

Deleted イベントを発生させます。

OnError(ErrorEventArgs)

Error イベントを発生させます。

OnRenamed(RenamedEventArgs)

Renamed イベントを発生させます。

ToString()

Component の名前 (存在する場合) を格納する String を返します。 このメソッドはオーバーライドできません。

(継承元 Component)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
WaitForChanged(WatcherChangeTypes)

監視する変更の種類を指定して、発生した変更についての固有な情報を格納する構造体を返す同期メソッド。

WaitForChanged(WatcherChangeTypes, Int32)

監視する変更の種類とタイムアウトまでの待機時間 (ミリ秒単位) を指定して、発生した変更についての固有な情報を格納する構造体を返す同期メソッド。

WaitForChanged(WatcherChangeTypes, TimeSpan)

監視する変更の種類に応じて、発生した変更に関する特定の情報を含む構造体を同期的に返します。

イベント

Changed

指定した Path のファイルまたはディレクトリが変更されたときに発生します。

Created

指定した Path のファイルまたはディレクトリが作成されたときに発生します。

Deleted

指定した Path のファイルまたはディレクトリが削除されたときに発生します。

Disposed

Dispose() メソッドの呼び出しによってコンポーネントが破棄されるときに発生します。

(継承元 Component)
Error

FileSystemWatcher のインスタンスが変更の監視を続けられない場合、または内部バッファー オーバーフローの場合に発生します。

Renamed

指定した Path のファイルまたはディレクトリの名前が変更されたときに発生します。

適用対象

こちらもご覧ください