FileSystemWatcher 类

定义

侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。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
[System.IO.IODescription("")]
[System.IO.IODescription("FileSystemWatcherDesc")]
public class FileSystemWatcher : System.ComponentModel.Component, System.ComponentModel.ISupportInitialize
type FileSystemWatcher = class
    inherit Component
    interface ISupportInitialize
Public Class FileSystemWatcher
Inherits Component
Implements ISupportInitialize
继承
FileSystemWatcher
属性
实现

示例

下面的示例创建一个FileSystemWatcher来监视运行时指定的目录。The following example creates a FileSystemWatcher to watch the directory specified at run time. 组件设置为监视LastWriteLastAccess时间中的更改、创建、删除或重命名目录中的文本文件。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.

#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();
}
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    private static void Run()
    {
        string[] args = 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.
        using (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 += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += 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: {e.OldFullPath} renamed to {e.FullPath}");
}
Imports System.IO
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 = 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.
        Using 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 Using
    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: {e.OldFullPath} renamed to {e.FullPath}")
    End Sub

End Class

注解

用于FileSystemWatcher监视指定目录中的更改。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.

若要监视所有文件中的更改,请Filter将属性设置为空字符串("")或使用通配符("**.")。To watch for changes in all files, set the Filter property to an empty string ("") or use wildcards ("*.*"). 若要查看特定文件,请将Filter属性设置为文件名。To watch a specific file, set the Filter property to the file name. 例如,若要监视文件 MyDoc 中的更改,请将Filter属性设置为 "MyDoc"。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 text files, set the Filter property to "*.txt".

可以在目录或文件中监视几种类型的更改。There are several types of changes you can watch for in a directory or file. 例如,你可以监视中Attributes的更改LastWrite 、日期Size和时间,或者文件或目录的。For example, you can watch for changes in Attributes, the LastWrite date and time, or the Size of files or directories. 这是通过将NotifyFilter属性设置为NotifyFilters值之一来完成的。This is done by setting the NotifyFilter property to one of the NotifyFilters values. 有关可以观看的更改类型的详细信息,请参阅NotifyFiltersFor more information on the type of changes you can watch, see NotifyFilters.

可以监视文件或目录的重命名、删除或创建。You can watch for renaming, deletion, or creation of files or directories. 例如,若要监视是否重命名了文本文件,请将Filter属性设置为 "* .txt" 并WaitForChanged使用Renamed为其参数指定的指定方法。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.

Windows 操作系统会将文件更改的组件通知到由FileSystemWatcher创建的缓冲区。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. 增加缓冲区InternalBufferSize的大小会消耗大量资源,因为它来自无法换出到磁盘的非分页内存,因此,请将缓冲区保持得足够小但足以避免丢失任何文件更改事件。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. 若要避免缓冲区溢出,请使用NotifyFilterIncludeSubdirectories属性,以便可以筛选出不需要的更改通知。To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

有关实例FileSystemWatcher的初始属性值的列表, FileSystemWatcher请参见构造函数。For a list of initial property values for an instance of FileSystemWatcher, see the FileSystemWatcher constructor.

使用FileSystemWatcher类时,请注意以下各项。Please note the following when using the FileSystemWatcher class.

  • 不会忽略隐藏的文件。Hidden files are not ignored.

  • 在某些系统中FileSystemWatcher ,使用短8.3 文件名格式对文件进行了更改。In some systems, FileSystemWatcher reports changes to files using the short 8.3 file name format. 例如,将 "LongFileName" 更改为 "LongFil ~。Lon "。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. 当直接调用方或派生类不具有完全信任权限时,将引发。SecurityExceptionA 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.

  • 可为InternalBufferSize通过网络监视目录的属性设置的最大大小为 64 KB。The maximum size you can set for the InternalBufferSize property for monitoring a directory over the network is 64 KB.

备注

FileSystemWatcher支持在 Windows 98 上运行。Running FileSystemWatcher on Windows 98 is not supported.

复制和移动文件夹Copying and moving folders

操作系统和FileSystemWatcher对象会将剪切和粘贴操作或移动操作解释为文件夹及其内容的重命名操作。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. 如果将包含文件的文件夹剪切并粘贴到被监视的文件夹中, FileSystemWatcher则对象只会将该文件夹报告为新文件夹,但不会报告其内容,因为它们实质上只是已重命名。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.

若要通知文件夹内容已移动或复制到监视的文件夹,请提供OnChanged下表中所述的和OnRenamed事件处理程序方法。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, DeletedChanged, 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. 例如,将文件从一个目录移到另一个目录时,可能OnChanged会引发OnCreatedOnDeleted个和某些事件。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. 同样,某些应用程序(例如,防病毒软件)可能会导致检测到FileSystemWatcher其他文件系统事件。Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

  • FileSystemWatcher可以监视磁盘,只要它们未被切换或删除。The FileSystemWatcher can watch disks as long as they are not switched or removed. FileSystemWatcher会为 cd 和 dvd 引发事件,因为时间戳和属性无法更改。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.

  • 如果在FileSystemWatcher windows XP Service Pack 1、windows 2000 SP2 或更早版本之前,多个对象正在监视相同的 UNC 路径,则只有其中一个对象会引发事件。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. 在运行 windows XP SP1 和更高版本、windows 2000 SP3 或更高版本或 windows Server FileSystemWatcher 2003 的计算机上,所有对象将引发相应的事件。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.

请注意, FileSystemWatcher当超过缓冲区大小时,可能会错过某个事件。Note that a FileSystemWatcher may miss an event when the buffer size is exceeded. 若要避免丢失事件,请遵循以下准则:To avoid missing events, follow these guidelines:

  • 通过设置InternalBufferSize属性来增加缓冲区大小。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.

构造函数

FileSystemWatcher()

初始化 FileSystemWatcher 类的新实例。Initializes a new instance of the FileSystemWatcher class.

FileSystemWatcher(String)

给定要监视的指定目录,初始化 FileSystemWatcher 类的新实例。Initializes a new instance of the FileSystemWatcher class, given the specified directory to monitor.

FileSystemWatcher(String, String)

给定要监视的指定目录和文件类型,初始化 FileSystemWatcher 类的新实例。Initializes a new instance of the FileSystemWatcher class, given the specified directory and type of files to monitor.

属性

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(继承自 Component)
DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
EnableRaisingEvents

获取或设置一个值,该值指示是否启用此组件。Gets or sets a value indicating whether the component is enabled.

Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 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

获取或设置 FileSystemWatcherISiteGets 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.

方法

BeginInit()

开始初始化在窗体上使用或由另一个组件使用的 FileSystemWatcherBegins 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.

(继承自 MarshalByRefObject)
Dispose()

释放 FileSystemWatcher 使用的非托管资源。Releases the unmanaged resources used by the FileSystemWatcher.

Dispose(Boolean)

释放由 FileSystemWatcher 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the FileSystemWatcher and optionally releases the managed resources.

EndInit()

结束在窗体上使用或由另一个组件使用的 FileSystemWatcher 的初始化。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.

(继承自 Object)
Finalize()

释放由当前实例所持有的资源。Releases the resources held by the current instance.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
OnChanged(FileSystemEventArgs)

引发 Changed 事件。Raises the Changed event.

OnCreated(FileSystemEventArgs)

引发 Created 事件。Raises the Created event.

OnDeleted(FileSystemEventArgs)

引发 Deleted 事件。Raises the Deleted event.

OnError(ErrorEventArgs)

引发 Error 事件。Raises the Error event.

OnRenamed(RenamedEventArgs)

引发 Renamed 事件。Raises the Renamed event.

ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 Component)
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.

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.

事件

Changed

当更改指定 Path 中的文件和目录时发生。Occurs when a file or directory in the specified Path is changed.

Created

当在指定 Path 中创建文件和目录时发生。Occurs when a file or directory in the specified Path is created.

Deleted

删除指定 Path 中的文件或目录时发生。Occurs when a file or directory in the specified Path is deleted.

Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)
Error

FileSystemWatcher 的实例无法继续监视更改或内部缓冲区溢出时发生。Occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.

Renamed

重命名指定 Path 中的文件或目录时发生。Occurs when a file or directory in the specified Path is renamed.

安全性

SecurityPermission
用于从ProcessStartInfo类派生。for deriving from the ProcessStartInfo class. 要求值: InheritanceDemand;命名权限集: FullTrustDemand value: InheritanceDemand; Named Permission Sets: FullTrust.

适用于

另请参阅