FileSystemWatcher 類別

定義

當目錄或目錄內的檔案變更時,接聽 (Listen) 檔案系統變更告知並引發事件。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. 如需您可以監看之變更類型的詳細資訊, NotifyFilters請參閱。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. 例如,若要監看文字檔的重新命名,請將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. LongExtension" 的變更可能會回報為 "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 ChangedCreatedDeletedChanged, 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多個物件在 Service Pack 1 之前或 windows 2000 SP2 或更早版本的 windows XP 中監看相同的 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 2003 的FileSystemWatcher電腦上,所有物件都會引發適當的事件。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

取得包含 IContainerComponentGets 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

取得或設定 ISiteFileSystemWatcherGets 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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
Dispose()

釋放由 FileSystemWatcher 使用的 Unmanaged 資源。Releases the unmanaged resources used by the FileSystemWatcher.

Dispose(Boolean)

釋放 FileSystemWatcher 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 名稱的 StringReturns 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.

適用於

另請參閱