Muokkaa

Jaa


FileSystemWatcher Class

Definition

Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

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
Inheritance
FileSystemWatcher
Inheritance
FileSystemWatcher
Attributes
Implements

Examples

The following example creates a FileSystemWatcher to watch the directory specified at run time. 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

Remarks

For more information about this API, see Supplemental API remarks for FileSystemWatcher.

Constructors

FileSystemWatcher()

Initializes a new instance of the FileSystemWatcher class.

FileSystemWatcher(String, String)

Initializes a new instance of the FileSystemWatcher class, given the specified directory and type of files to monitor.

FileSystemWatcher(String)

Initializes a new instance of the FileSystemWatcher class, given the specified directory to monitor.

Properties

CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container

Gets the IContainer that contains the Component.

(Inherited from Component)
DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
EnableRaisingEvents

Gets or sets a value indicating whether the component is enabled.

Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
Filter

Gets or sets the filter string used to determine what files are monitored in a directory.

Filters

Gets the collection of all the filters used to determine what files are monitored in a directory.

IncludeSubdirectories

Gets or sets a value indicating whether subdirectories within the specified path should be monitored.

InternalBufferSize

Gets or sets the size (in bytes) of the internal buffer.

NotifyFilter

Gets or sets the type of changes to watch for.

Path

Gets or sets the path of the directory to watch.

Site

Gets or sets an ISite for the FileSystemWatcher.

SynchronizingObject

Gets or sets the object used to marshal the event handler calls issued as a result of a directory change.

Methods

BeginInit()

Begins the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases the unmanaged resources used by the FileSystemWatcher.

Dispose()

Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean)

Releases the unmanaged resources used by the FileSystemWatcher and optionally releases the managed resources.

EndInit()

Ends the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnChanged(FileSystemEventArgs)

Raises the Changed event.

OnCreated(FileSystemEventArgs)

Raises the Created event.

OnDeleted(FileSystemEventArgs)

Raises the Deleted event.

OnError(ErrorEventArgs)

Raises the Error event.

OnRenamed(RenamedEventArgs)

Raises the Renamed event.

ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component)
ToString()

Returns a string that represents the current object.

(Inherited from Object)
WaitForChanged(WatcherChangeTypes, Int32)

A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor and the time (in milliseconds) to wait before timing out.

WaitForChanged(WatcherChangeTypes, TimeSpan)

Synchronously returns a structure that contains specific information on the change that occurred, given the type of change to monitor.

WaitForChanged(WatcherChangeTypes)

A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor.

Events

Changed

Occurs when a file or directory in the specified Path is changed.

Created

Occurs when a file or directory in the specified Path is created.

Deleted

Occurs when a file or directory in the specified Path is deleted.

Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
Error

Occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.

Renamed

Occurs when a file or directory in the specified Path is renamed.

Applies to

See also