Input and Output
  Read a text file
  List a directory
  Create a log file
  Read and write large files
  Read and write binary data
  Watch file system changes

Get URL for this page

How Do I...Watch file system changes?

Use the FileSystemWatcher component to monitor a file system and react when changes to it occur. This makes it possible for you to quickly and easily launch business processes when certain files or directories are created, modified, or deleted. For example, suppose you and a group of coworkers are collaborating on a document that is stored on a shared directory on your server. Using the FileSystemWatcher component, you can easily program your application to watch for changes to the shared directory. When a change is detected, the component can run processing that notifies each of the group members through email.

This sample illustrates how to use a FileSystemWatcher to watch for any changes, renaming, creation, and deletion of any files in the specified directory. The application takes the directory that you wish to watch as the only argument.

Try running the sample as follows:

> Watcher.exe c:\

Now, open the c:\ directory and try creating, modifying and deleting a file in the directory. Observe the sample application printing an appropriate message to the console window.

In its simplest form, using a FileSystemWatcher involves:

  1. Creating a new instance of the component and specifing the directory to watch:

    
    Dim watcher As FileSystemWatcher = New FileSystemWatcher()
    watcher.Path= "c:\Foo"
    
    VB

  2. Adding event handler[s]:

    
    AddHandler watcher.Changed, AddressOf OnChanged
    AddHandler watcher.Created, AddressOf OnChanged
    
    VB

  3. Specifying what the application should do when a change occurs:

    
    Public Sub OnChanged(source As Object, e As FileSystemEventArgs)
      Console.Write("File: {0} {1}", e.FullPath, e.ChangeType)
    End Sub
    
    VB

  4. Enabling the component:

    
    watcher.EnableRaisingEvents = True
    
    VB

Example

 
VB Watcher.exe

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.