Skip to main content
.NET Framework Class Library
FileSystemWatcher Class

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

To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:   System.IO
Assembly:  System (in System.dll)
Syntax
<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_0%]("FileSystemWatcherDesc")> _
<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_1%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_2%].InheritanceDemand, Name := "FullTrust")> _
<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_3%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_4%].LinkDemand, Name := "FullTrust")> _
Public Class FileSystemWatcher _
	Inherits [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_5%] _
	Implements [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_0_0_6%]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_0%]("FileSystemWatcherDesc")]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_1%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_2%].InheritanceDemand, Name = "FullTrust")]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_3%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_4%].LinkDemand, Name = "FullTrust")]
public class FileSystemWatcher : [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_5%], 
	[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_1_0_6%]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_0%](L"FileSystemWatcherDesc")]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_1%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_2%]::InheritanceDemand, Name = L"FullTrust")]
[[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_3%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_4%]::LinkDemand, Name = L"FullTrust")]
public ref class FileSystemWatcher : public [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_5%], 
	[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_2_0_6%]
[<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_0%]("FileSystemWatcherDesc")>]
[<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_1%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_2%].InheritanceDemand, Name = "FullTrust")>]
[<[%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_3%]([%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_4%].LinkDemand, Name = "FullTrust")>]
type FileSystemWatcher =  
    class 
        inherit [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_5%] 
        interface [%$TOPIC/x7t1d0ky_en-us_VS_110_3_0_3_0_6%] 
    end

The FileSystemWatcher type exposes the following members.

Constructors
  NameDescription
Public method FileSystemWatcherInitializes a new instance of the FileSystemWatcher class.
Public method FileSystemWatcher(String)Initializes a new instance of the FileSystemWatcher class, given the specified directory to monitor.
Public method FileSystemWatcher(String, String)Initializes a new instance of the FileSystemWatcher class, given the specified directory and type of files to monitor.
Top
Properties
  NameDescription
Protected property CanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property ContainerGets the IContainer that contains the Component. (Inherited from Component.)
Protected property DesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property EnableRaisingEventsGets or sets a value indicating whether the component is enabled.
Protected property EventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property FilterGets or sets the filter string used to determine what files are monitored in a directory.
Public property IncludeSubdirectoriesGets or sets a value indicating whether subdirectories within the specified path should be monitored.
Public property InternalBufferSizeGets or sets the size (in bytes) of the internal buffer.
Public property NotifyFilterGets or sets the type of changes to watch for.
Public property PathGets or sets the path of the directory to watch.
Public property SiteGets or sets an ISite for the FileSystemWatcher. (Overrides ComponentSite.)
Public property SynchronizingObjectGets or sets the object used to marshal the event handler calls issued as a result of a directory change.
Top
Methods
  NameDescription
Public method BeginInitBegins the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.
Public method CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method DisposeReleases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean)Releases the unmanaged resources used by the FileSystemWatcher and optionally releases the managed resources. (Overrides ComponentDispose(Boolean).)
Public method EndInitEnds the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.
Public method Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method FinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method OnChangedRaises the Changed event.
Protected method OnCreatedRaises the Created event.
Protected method OnDeletedRaises the Deleted event.
Protected method OnErrorRaises the Error event.
Protected method OnRenamedRaises the Renamed event.
Public method ToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Public method 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.
Public method 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.
Top
Events
  NameDescription
Public event ChangedOccurs when a file or directory in the specified Path is changed.
Public event CreatedOccurs when a file or directory in the specified Path is created.
Public event DeletedOccurs when a file or directory in the specified Path is deleted.
Public event DisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event ErrorOccurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.
Public event RenamedOccurs when a file or directory in the specified Path is renamed.
Top
Remarks
NoteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

To watch for changes in all files, set the Filter property to an empty string ("") or use wildcards ("*.*"). To watch a specific file, set the Filter property to the file name. 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. For example, to watch for changes in text files, set the Filter property to "*.txt".

There are several types of changes you can watch for in a directory or file. For example, you can watch for changes in Attributes, the LastWrite date and time, or the Size of files or directories. This is done by setting the NotifyFilter property to one of the NotifyFilters values. For more information on the type of changes you can watch, see NotifyFilters.

You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter.

The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

For a list of initial property values for an instance of FileSystemWatcher, see the FileSystemWatcher constructor.

Please note the following when using the FileSystemWatcher class.

  • Hidden files are not ignored.

  • In some systems, FileSystemWatcher reports changes to files using the short 8.3 file name format. For example, a change to "LongFileName.LongExtension" could be reported as "LongFil~.Lon".

  • This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands.

  • The maximum size you can set for the InternalBufferSize property for monitoring a directory over the network is 64 KB.

NoteNote

Running FileSystemWatcher on Windows 98 is not supported.

Copying and moving folders

The operating system and FileSystemWatcher object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents. If you cut and paste a folder with files into a folder being watched, the FileSystemWatcher object reports only the folder as new, but not its contents because they are essentially only renamed.

To be notified that the contents of folders have been moved or copied into a watched folder, provide OnChanged and OnRenamed event handler methods as suggested in the following table.

Event Handler

Events Handled

Performs

OnChanged

Changed, Created, Deleted

Report changes in file attributes, created files, and deleted files.

OnRenamed

Renamed

List the old and new paths of renamed files and folders, expanding recursively if needed.

Events and Buffer Sizes

Note that several factors can affect which file system change events are raised, as described by the following:

  • Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

  • The FileSystemWatcher can watch disks as long as they are not switched or removed. The FileSystemWatcher does not raise events for CDs and DVDs, because time stamps and properties cannot change. Remote computers must have one of the required platforms installed for the component to function properly.

  • If multiple FileSystemWatcher objects are watching the same UNC path in Windows XP prior to Service Pack 1, or Windows 2000 SP2 or earlier, then only one of the objects will raise an event. On machines running Windows XP SP1 and newer, Windows 2000 SP3 or newer or Windows Server 2003, all FileSystemWatcher objects will raise the appropriate events.

Note that a FileSystemWatcher may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines:

  • Increase the buffer size by setting the InternalBufferSize property.

  • Avoid watching files with long file names, because a long file name contributes to filling up the buffer. Consider renaming these files using shorter names.

  • Keep your event handling code as short as possible.

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.

Use the System.Diagnostics and System.IO namespaces for this example.

Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Security.Permissions

Public Class Watcher

    Public Shared Sub Main()
	
         Run()

    End Sub

    <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
    Private Shared Sub Run

      Dim args() As String = System.Environment.GetCommandLineArgs()
        ' If a directory is not specified, exit the program. 
        If args.Length <> 2 Then 
            ' Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)")
            Return 
        End If 

        ' Create a new FileSystemWatcher and set its properties. 
        Dim watcher As New FileSystemWatcher()
        watcher.Path = args(1)
        ' Watch for changes in LastAccess and LastWrite times, and 
        ' the renaming of files or directories. 
        watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)
        ' Only watch text files.
        watcher.Filter = "*.txt" 

        ' Add event handlers. 
        AddHandler watcher.Changed, AddressOf OnChanged
        AddHandler watcher.Created, AddressOf OnChanged
        AddHandler watcher.Deleted, AddressOf OnChanged
        AddHandler watcher.Renamed, AddressOf OnRenamed

        ' Begin watching.
        watcher.EnableRaisingEvents = True 

        ' Wait for the user to quit the program.
        Console.WriteLine("Press 'q' to quit the sample.")
        While Chr(Console.Read()) <> "q"c
        End While 
    End Sub 

    ' Define the event handlers. 
    Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs)
        ' Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine("File: " & e.FullPath & " " & e.ChangeType)
    End Sub     

    Private Shared Sub OnRenamed(source As Object, e As RenamedEventArgs)
        ' Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
    End Sub 

End Class
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
    Run();

    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program. 
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers. 
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;

public ref class Watcher
{
private:
   // Define the event handlers. 
   static void OnChanged( Object^ /*source*/, FileSystemEventArgs^ e )
   {
      // Specify what is done when a file is changed, created, or deleted.
      Console::WriteLine( "File: {0} {1}", e->FullPath, e->ChangeType );
   }

   static void OnRenamed( Object^ /*source*/, RenamedEventArgs^ e )
   {
      // Specify what is done when a file is renamed.
      Console::WriteLine( "File: {0} renamed to {1}", e->OldFullPath, e->FullPath );
   }

public:
   [PermissionSet(SecurityAction::Demand, Name="FullTrust")]
   int static run()
   {
      array<String^>^args = System::Environment::GetCommandLineArgs();

      // If a directory is not specified, exit program. 
      if ( args->Length != 2 )
      {
         // Display the proper way to call the program.
         Console::WriteLine( "Usage: Watcher.exe (directory)" );
         return 0;
      }

      // Create a new FileSystemWatcher and set its properties.
      FileSystemWatcher^ watcher = gcnew FileSystemWatcher;
      watcher->Path = args[ 1 ];

      /* Watch for changes in LastAccess and LastWrite times, and 
          the renaming of files or directories. */
      watcher->NotifyFilter = static_cast<NotifyFilters>(NotifyFilters::LastAccess |
            NotifyFilters::LastWrite | NotifyFilters::FileName | NotifyFilters::DirectoryName);

      // Only watch text files.
      watcher->Filter = "*.txt";

      // Add event handlers.
      watcher->Changed += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Created += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Deleted += gcnew FileSystemEventHandler( Watcher::OnChanged );
      watcher->Renamed += gcnew RenamedEventHandler( Watcher::OnRenamed );

      // Begin watching.
      watcher->EnableRaisingEvents = true;

      // Wait for the user to quit the program.
      Console::WriteLine( "Press \'q\' to quit the sample." );
      while ( Console::Read() != 'q' );

      return 0;
   }
};

int main() {
   Watcher::run();
}
Version Information

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
.NET Framework Security
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.