FileSystemWatcher 类

侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。

**命名空间:**System.IO
**程序集:**System(在 system.dll 中)

语法

声明
Public Class FileSystemWatcher
    Inherits Component
    Implements ISupportInitialize
用法
Dim instance As FileSystemWatcher
public class FileSystemWatcher : Component, ISupportInitialize
public ref class FileSystemWatcher : public Component, ISupportInitialize
public class FileSystemWatcher extends Component implements ISupportInitialize
public class FileSystemWatcher extends Component implements ISupportInitialize

备注

使用 FileSystemWatcher 监视指定目录中的更改。可监视指定目录中的文件或子目录的更改。可以创建一个组件来监视本地计算机、网络驱动器或远程计算机上的文件。

若要通过文件扩展名监视所有文件中的更改,请将 Filter 属性设置为空字符串 ("") 或使用通配符(“*.*”)。若要监视特定的文件,请将 Filter 属性设置为该文件名。例如,若要监视文件 MyDoc.txt 中的更改,请将 Filter 属性设置为“MyDoc.txt”。也可以监视特定类型文件中的更改。例如,若要监视文本文件中的更改,请将 Filter 属性设置为“*.txt”。

可监视目录或文件中的若干种更改。例如,可监视文件或目录的 AttributesLastWrite 日期和时间或 Size 方面的更改。通过将 NotifyFilter 属性设置为 NotifyFilters 值之一来达到此目的。有关可监视的更改类型的更多信息,请参见 NotifyFilters

可监视文件或目录的重命名、删除或创建。例如,若要监视文本文件的重命名,请将 Filter 属性设置为“*.txt”,并使用为其参数指定的 Renamed 来调用 WaitForChanged 方法。

Windows 操作系统在 FileSystemWatcher 创建的缓冲区中通知组件文件发生更改。如果短时间内有很多更改,则缓冲区可能会溢出。这将导致组件失去对目录更改的跟踪,并且它将只提供一般性通知。使用 InternalBufferSize 属性来增加缓冲区大小的开销较大,因为它来自无法换出到磁盘的非页面内存,所以应确保缓冲区大小适中(尽量小,但也要有足够大小以便不会丢失任何文件更改事件)。若要避免缓冲区溢出,请使用 NotifyFilterIncludeSubdirectories 属性,以便可以筛选掉不想要的更改通知。

有关 FileSystemWatcher 的实例的初始属性值列表,请参见 FileSystemWatcher 构造函数。

使用 FileSystemWatcher 类时,请注意以下事项。

  • 不忽略隐藏文件。

  • 在某些系统中,FileSystemWatcher 使用 8.3 短文件名格式报告文件更改。例如,对“LongFileName.LongExtension”的更改可能报告为“LongFi~.Lon”。

  • 此类在应用于所有成员的类级别上包含一个链接要求和一个继承要求。如果直接调用方或派生类不具有完全信任权限,则会引发 SecurityException。有关安全要求的详细信息,请参见 链接要求

复制和移动文件夹

操作系统和 FileSystemWatcher 对象将剪切和粘贴操作或移动操作解释为对文件夹及其内容的重命名操作。如果将包含文件的文件夹剪切并粘贴到受监视的文件夹中,则 FileSystemWatcher 对象仅将文件夹报告为新建,但不能将其内容报告为新建,因为实际上只是对它们进行了重命名。

若要接收已将文件夹内容移动或复制到受监视的文件夹中的通知,请根据下表中的建议提供 OnChangedOnRenamed 事件处理程序方法。

事件处理程序

已处理的事件

执行

OnChanged

Changed, Created, Deleted

报告文件属性的更改、创建的文件和删除的文件。

OnRenamed

Renamed

列出重命名的文件和文件夹的新旧路径,需要时可以递归扩展。

事件和缓冲区大小

请注意,有几个因素可能影响引发哪些文件系统更改事件,如下所述:

  • 公共文件系统操作可能会引发多个事件。例如,将文件从一个目录移到另一个目录时,可能会引发若干 OnChanged 以及一些 OnCreatedOnDeleted 事件。移动文件是一个包含多个简单操作的复杂操作,因此会引发多个事件。同样,有些应用程序(例如,防病毒软件)可能会导致可由 FileSystemWatcher 检测到的其他文件系统事件。

  • 只要磁盘没有切换或移除,FileSystemWatcher 就可监视它们。因为 CD 和 DVD 的时间戳和属性不能更改,所以 FileSystemWatcher 不为 CD 和 DVD 引发事件。要使该组件正常运行,远程计算机必须具有所需的这些平台之一。但是,无法从 Windows NT 4.0 计算机监视远程 Windows NT 4.0 计算机。

  • 在 Windows XP(Service Pack 1 之前版本)或者 Windows 2000 SP2 或更低版本中,如果多个 FileSystemWatcher 对象正在监视同一个 UNC 路径,则只有其中一个对象会引发事件。在运行 Windows XP SP1 及之后版本、Windows 2000 SP3 或之后版本或者 Windows Server 2003 的计算机上,所有 FileSystemWatcher 对象都将引发相应的事件。

  • 设置 Filter 不会减少进入缓冲区中的内容。

请注意,由于 Windows 操作系统的依赖项,当丢失某个事件或超出缓冲区大小时,FileSystemWatcher 不会引发 Error 事件。若要防止丢失事件,请遵从这些准则:

  • 使用 InternalBufferSize 属性增加缓冲区大小可以防止丢失文件系统更改事件。

  • 避免监视带有长文件名的文件。考虑使用较短的名称进行重命名。

  • 尽可能使事件处理代码短小。

示例

下面的示例创建一个 FileSystemWatcher,以便在运行时监视指定的目录。组件设置为监视 LastWriteLastAccess 时间方面的更改,以及目录中文本文件的创建、删除或重命名。如果更改、创建或删除文件,文件路径将被输出到控制台。在文件重命名后,旧路径和新路径都输出到控制台。

在此示例中使用 System.DiagnosticsSystem.IO 命名空间。

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
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);
    }
}
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' )
         ;
   }
};

int main() {
   Watcher::run();
}
public class Watcher
{
    public static void main(String[] args1)
    {
    Run();
    } 

    /** @attribute 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.set_Path(args[1]);

        /* Watch for changes in LastAccess and LastWrite times, and 
           the renaming of files or directories.
         */
        watcher.set_NotifyFilter
            (NotifyFilters.LastAccess |NotifyFilters.LastWrite |
            NotifyFilters.FileName | NotifyFilters.DirectoryName);

        // Only watch text files.
        watcher.set_Filter("*.txt");

        // Add event handlers.
        watcher.add_Changed(new FileSystemEventHandler(OnChanged));
        watcher.add_Created(new FileSystemEventHandler(OnChanged));
        watcher.add_Deleted(new FileSystemEventHandler(OnChanged));
        watcher.add_Renamed(new RenamedEventHandler(OnRenamed));

        // Begin watching.
        watcher.set_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.get_FullPath() + " " 
            + e.get_ChangeType()));
    } //OnChanged

    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.get_OldFullPath(),e.get_FullPath());
    } //OnRenamed
} //Watcher

.NET Framework 安全性

继承层次结构

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.IO.FileSystemWatcher

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

请参见

参考

FileSystemWatcher 成员
System.IO 命名空间
FileSystemWatcher.NotifyFilter
NotifyFilters
FileSystemEventArgs 类
FileSystemEventHandler 委托
Filter
IncludeSubdirectories
InternalBufferOverflowException
RenamedEventArgs
RenamedEventHandler
WaitForChangedResult
WatcherChangeTypes