You are on page 1of 7

FileSystemWatcher Class (System.

IO)

Page 1 of 7

2010 Microsoft Corporation. All rights reserved.

.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. Namespace: System.IO Assembly: System (in system.dll)

Syntax
Visual Basic (Declaration)

Public Class FileSystemWatcher Inherits Component Implements ISupportInitialize

Visual Basic (Usage)

Dim instance As FileSystemWatcher

C#

public class FileSystemWatcher : Component, ISupportInitialize

C++

public ref class FileSystemWatcher : public Component, ISupportInitialize

J#

public class FileSystemWatcher extends Component implements ISupportInitialize

JScript

public class FileSystemWatcher extends Component implements ISupportInitialize

Remarks
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 with a file extension, set the Filter [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.filter(VS.80).aspx ] 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 [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.notifyfilter(VS.80).aspx ] property to one of the NotifyFilters [ http://msdn.microsoft.com/en-us/library/system.io.notifyfilters(VS.80).aspx ] 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 [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.waitforchanged(VS.80).aspx ] method with a Renamed [ http://msdn.microsoft.com/enus/library/system.io.watcherchangetypes.renamed(VS.80).aspx ] 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 [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.internalbuffersize(VS.80).aspx ] 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 [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.includesubdirectories(VS.80).aspx ] properties so you can filter out unwanted change notifications. For a list of initial property values for an instance of FileSystemWatcher, see the FileSystemWatcher

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 2 of 7

[ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filesystemwatcher(VS.80).aspx ] 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 "LongFi~.Lon". This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException [ http://msdn.microsoft.com/en-us/library/system.security.securityexception(VS.80).aspx ] 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 [ http://msdn.microsoft.com/en-us/library/hzsc022c(VS.80).aspx ] . 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 [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.onchanged(VS.80).aspx ] and OnRenamed [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.onrenamed(VS.80).aspx ] event handler methods as suggested in the following table. Event Handler Events Handled Performs

OnChanged

Changed [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.changed(VS.80).aspx ] , Created [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created (VS.80).aspx ] , Deleted [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.deleted(VS.80).aspx ] Renamed [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.renamed(VS.80).aspx ]

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

OnRenamed

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 [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.oncreated(VS.80).aspx ] and OnDeleted [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.ondeleted(VS.80).aspx ] 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. However, you cannot watch a remote Windows NT 4.0 computer from a Windows NT 4.0 computer. 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. Setting the Filter does not decrease what goes into the buffer. Note that a FileSystemWatcher does not raise an Error [ http://msdn.microsoft.com/enus/library/system.io.filesystemwatcher.error(VS.80).aspx ] event when an event is missed or when the buffer size is exceeded, due to dependencies with the Windows operating system. To keep from missing events, follow these guidelines: Increasing the buffer size with the InternalBufferSize property can prevent missing file system change events. Avoid watching files with long file names. Consider renaming using shorter names. Keep your event handling code as short as possible.

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 3 of 7

Example
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 [ http://msdn.microsoft.com/en-us/library/system.diagnostics(VS.80).aspx ] and System.IO [ http://msdn.microsoft.com/en-us/library/system.io(VS.80).aspx ] namespaces for this example. Visual Basic Copy Code

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, AddHandler watcher.Created, AddHandler watcher.Deleted, AddHandler watcher.Renamed,

AddressOf AddressOf AddressOf AddressOf

OnChanged OnChanged OnChanged 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

C#

Copy Code

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

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 4 of 7

} [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 watcher.Created += new watcher.Deleted += new watcher.Renamed += new

FileSystemEventHandler(OnChanged); FileSystemEventHandler(OnChanged); FileSystemEventHandler(OnChanged); 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); } }

C++

Copy Code

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();

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 5 of 7

// 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 watcher->Created += gcnew watcher->Deleted += gcnew watcher->Renamed += gcnew

FileSystemEventHandler( Watcher::OnChanged ); FileSystemEventHandler( Watcher::OnChanged ); FileSystemEventHandler( Watcher::OnChanged ); 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(); }

J#

Copy Code

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");

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 6 of 7

// Add event handlers. watcher.add_Changed(new watcher.add_Created(new watcher.add_Deleted(new watcher.add_Renamed(new

FileSystemEventHandler(OnChanged)); FileSystemEventHandler(OnChanged)); FileSystemEventHandler(OnChanged)); 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 Security


SecurityPermission [ http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermission(VS.80).aspx ] for calling members of ProcessStartInfo [ http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo (VS.80).aspx ] . Demand value: LinkDemand [ http://msdn.microsoft.com/enus/library/system.security.permissions.securityaction.linkdemand(VS.80).aspx ] ; Named Permission Sets: FullTrust. SecurityPermission for deriving from the ProcessStartInfo class. Demand value: InheritanceDemand [ http://msdn.microsoft.com/en-us/library/system.security.permissions.securityaction.inheritancedemand(VS.80).aspx ] ; Named Permission Sets: FullTrust.

Inheritance Hierarchy
System.Object [ http://msdn.microsoft.com/en-us/library/system.object(VS.80).aspx ] System.MarshalByRefObject [ http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject(VS.80).aspx ] System.ComponentModel.Component [ http://msdn.microsoft.com/en-us/library/system.componentmodel.component (VS.80).aspx ] System.IO.FileSystemWatcher

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.

Platforms
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 The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements [ http://msdn.microsoft.com/en-us/library/8z6watww(VS.80).aspx ] .

Version Information
.NET Framework Supported in: 2.0, 1.1, 1.0

See Also
Reference FileSystemWatcher Members [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher_members(VS.80).aspx ] System.IO Namespace [ http://msdn.microsoft.com/en-us/library/system.io(VS.80).aspx ] FileSystemWatcher.NotifyFilter [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.notifyfilter(VS.80).aspx ] NotifyFilters [ http://msdn.microsoft.com/en-us/library/system.io.notifyfilters(VS.80).aspx ] FileSystemEventArgs Class [ http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(VS.80).aspx ] FileSystemEventHandler Delegate [ http://msdn.microsoft.com/en-us/library/system.io.filesystemeventhandler(VS.80).aspx ] Filter [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter(VS.80).aspx ] IncludeSubdirectories [ http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.includesubdirectories(VS.80).aspx ]

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010

FileSystemWatcher Class (System.IO)

Page 7 of 7

InternalBufferOverflowException [ http://msdn.microsoft.com/en-us/library/system.io.internalbufferoverflowexception (VS.80).aspx ] RenamedEventArgs [ http://msdn.microsoft.com/en-us/library/system.io.renamedeventargs(VS.80).aspx ] RenamedEventHandler [ http://msdn.microsoft.com/en-us/library/system.io.renamedeventhandler(VS.80).aspx ] WaitForChangedResult [ http://msdn.microsoft.com/en-us/library/system.io.waitforchangedresult(VS.80).aspx ] WatcherChangeTypes [ http://msdn.microsoft.com/en-us/library/t6xf43e0(VS.80).aspx ]

Tags:

Community Content
specific file name?
Last Edit 3:54 AM by lluke

This is working, but only giving the directory (FullPath), how can I force it to display the specific name of the file that changed? <br /><br /> Thanks,<br /><br /> Luke.<br />

Tags: contentbug

UNC source on Windows 2000 SP4 still firing on one watcher object

Last Edit 12:32 PM by Niels Vrolijk

Although this document states: "<span>If multiple <b>FileSystemWatcher</b> 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 <b>FileSystemWatcher</b> objects will raise the appropriate events." I also got this behavior on a machine running Windows 2000 Server SP4.<br /></span>

Tags:

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.80,printer).aspx

31/8/2010