Issue dated - 31st May 2004

-


Previous Issues

CURRENT ISSUE
INDIA NEWS
NEWS ANALYSIS
COMPANY WATCH
INDIA TRENDS
PRODUCT
COLUMNS
TECH FORUM

THE C# COLUMN

BETWEEN THE BYTES
TECHNOLOGY
SPECIALS <NEW>
Symantec Report
Security Headquarters
JobsDB
MINDPRINTS
HMA BANKBIZ
EC SERVICES
ARCHIVES/SEARCH
IT APPOINTMENTS
Openings At Jobstreet.com
WRITE TO US
SUBSCRIBE/RENEW
CUSTOMER SERVICE
ADVERTISE
ABOUT US

 Network Sites
  IT People
  Network Magazine
  Business Traveller
  Exp. Hotelier & Caterer
  Exp. Travel & Tourism
  Exp. Pharma Pulse
  Exp. Healthcare Mgmt.
  Express Textile
 Group Sites
  ExpressIndia
  Indian Express
  Financial Express

 
Front Page > TechSpace > Story Print this Page|  Email this page

The C# column

Using the FileSystemWatcher Component

In this article we will walk through the process of using the FileSystemWatcher component and watching the changes made to a subfolder/files of a selected folder.

The FileSystemWatcher component can keep track of creation, deletion, changing and renaming of a file/folder. It conveys to the application information about changes done to the file system by throwing events. It throws the Created, Deleted, Changed and Renamed events respectively. The name and path of the file/folder being changed is also made available in the event handlers.

The FileSystemWatcher component can watch files on a local computer, a network drive, or a remote computer. We can specify which files to watch by setting the appropriate value in the Filter property. If we wish to watch all the files we must set the Filter property to an empty string (“”). To watch a specific file, we must assign that filename to the Filter property. We can also use wildcards to specify certain type of file. For example, to watch for changes in EXE files, we can set the Filter property to “*.exe”.

The component has a property called NotifyFilter that can be used to specify the types of changes viz. changes in attribute, last write date and time, size, etc.

Having this much of knowledge about FileSystemWatcher component in hand, we can now use the component in our application.

We will create an application that uses the FileSystemWatcher control to keep watch on the folder selected by the user, an watch whether a file/folder is created, changed or deleted.

Create a WinForm application and put the controls on the form as shown in following figure.

We have added three list boxes to list the files/folders being created, changed or deleted. The ‘Watch Folder’ button allows the user to select a folder to watch. The path of the selected folder gets displayed on the label placed next to the ‘Watch Folder’ button. The ‘Clear’ button allows the user to delete the items listed in the list box having input focus.

In addition to these controls, add the FolderBrowserDialog control from the ‘Windows Forms’ tab and FileSystemWatcher component from the ‘Components’ tab of the ToolBox. The controls, their names and event handlers are given in the following table.

Control Name Handler
‘Created’ list box listcreate -
‘Changed’ list box listchange -
‘Deleted’ list boxlistdelete -
‘Watch Folder’ button butwatch butwatch_Click
‘Clear’ button butclear butclear_Click
FileSystemWatcher watcher -
FolderBrowserDialog browser  

Add handlers for the Created, Deleted and Changed events. Also Set the IncludeSubdirectories property of the FileSystemWatcher component to true.

When the application is run, the user has to first select a folder to watch. He can do so by clicking the ‘Watch Folder’ button. We have displayed the ‘Browse For Folder’ standard dialog box in which user can select the folder. The dialog is displayed by calling the ShowDialog( ) method as shown below.

private void butwatch_Click ( object sender, System.EventArgs e )
{
  if ( browser.ShowDialog( ) == DialogResult.OK )
   {
      watcher.Path =  browser.SelectedPath ;
      label1.Text = browser.SelectedPath ;
   }
}

We have specified the folder to watch by setting the Path property of the FileSystemWatcher class to the path of selected folder. The path of selected folder is retrieved from the SelectedPath property of the FolderBrowserDialog class. We have displayed the path on the label.

The handlers added for the FileSystemWatcher events are given below.

private void watcher_Changed ( object sender, System.IO.FileSystemEventArgs e )
{
   listchange.Items.Add ( e.FullPath ) ;
}
   private void watcher_Created ( object sender,
   System.IO.FileSystemEventArgs e )
   {
      listcreate.Items.Add ( e.FullPath ) ;
   }
   private void watcher_Deleted ( object sender,
   System.IO.FileSystemEventArgs e )
   {
      listdelete.Items.Add ( e.FullPath ) ;
   }

In these handlers we have only added the full path of the file/folder being changed, created or deleted in the respective list boxes.

To clear a list box, the user has to select an item in that list box and click the ‘Clear’ button. The handler for the ‘Clear’ button is given below.

private void butclear_Click ( object sender, System.EventArgs e )
{
   if ( listcreate.SelectedIndex != -1 )
   listcreate.Items.Clear( ) ;
   else
      {
        if ( listchange.SelectedIndex != -1 )
        listchange.Items.Clear( ) ;
   else
        if ( listdelete.SelectedIndex != -1 )
        listdelete.Items.Clear( ) ;
      }
}

The SelectedIndex property returns –1 if no item is currently selected. If any item is selected, the condition becomes true and the list box gets cleared.

The following figure shows our application at work. The list boxes seem to have trapped a few files being changed.

In this article we will walk through the process of using the FileSystemWatcher component and watching the changes made to a subfolder/files of a selected folder.

The FileSystemWatcher component can keep track of creation, deletion, changing and renaming of a file/folder. It conveys to the application information about changes done to the file system by throwing events. It throws the Created, Deleted, Changed and Renamed events respectively. The name and path of the file/folder being changed is also made available in the event handlers.

The FileSystemWatcher component can watch files on a local computer, a network drive, or a remote computer. We can specify which files to watch by setting the appropriate value in the Filter property. If we wish to watch all the files we must set the Filter property to an empty string (“”). To watch a specific file, we must assign that filename to the Filter property. We can also use wildcards to specify certain type of file. For example, to watch for changes in EXE files, we can set the Filter property to “*.exe”.

The component has a property called NotifyFilter that can be used to specify the types of changes viz. changes in attribute, last write date and time, size, etc.

Having this much of knowledge about FileSystemWatcher component in hand, we can now use the component in our application.

We will create an application that uses the FileSystemWatcher control to keep watch on the folder selected by the user, an watch whether a file/folder is created, changed or deleted.

Create a WinForm application and put the controls on the form as shown in following figure.

We have added three list boxes to list the files/folders being created, changed or deleted. The ‘Watch Folder’ button allows the user to select a folder to watch. The path of the selected folder gets displayed on the label placed next to the ‘Watch Folder’ button. The ‘Clear’ button allows the user to delete the items listed in the list box having input focus.

In addition to these controls, add the FolderBrowserDialog control from the ‘Windows Forms’ tab and FileSystemWatcher component from the ‘Components’ tab of the ToolBox. The controls, their names and event handlers are given in the following table.

Add handlers for the Created, Deleted and Changed events. Also Set the IncludeSubdirectories property of the FileSystemWatcher component to true.

When the application is run, the user has to first select a folder to watch. He can do so by clicking the ‘Watch Folder’ button. We have displayed the ‘Browse For Folder’ standard dialog box in which user can select the folder. The dialog is displayed by calling the ShowDialog( ) method as shown below.

private void butwatch_Click ( object sender, System.EventArgs e )
{
   if ( browser.ShowDialog( ) == DialogResult.OK )
   {
      watcher.Path = browser.SelectedPath ;
      label1.Text = browser.SelectedPath ;
   }
}

We have specified the folder to watch by setting the Path property of the FileSystemWatcher class to the path of selected folder. The path of selected folder is retrieved from the SelectedPath property of the FolderBrowserDialog class. We have displayed the path on the label.

The handlers added for the FileSystemWatcher events are given below.

private void watcher_Changed ( object sender,
System.IO.FileSystemEventArgs e )
{
    listchange.Items.Add ( e.FullPath ) ;
}
    private void watcher_Created ( object sender,
System.IO.FileSystemEventArgs e )
{
    listcreate.Items.Add ( e.FullPath ) ;
}
   private void watcher_Deleted ( object sender,
System.IO.FileSystemEventArgs e )
{
   listdelete.Items.Add ( e.FullPath ) ;
}

In these handlers we have only added the full path of the file/folder being changed, created or deleted in the respective list boxes.

To clear a list box, the user has to select an item in that list box and click the ‘Clear’ button. The handler for the ‘Clear’ button is given below.

private void butclear_Click ( object sender, System.EventArgs e )
{
   if ( listcreate.SelectedIndex != -1 )
   listcreate.Items.Clear( ) ;
   else
  {
    if ( listchange.SelectedIndex != -1 )
    listchange.Items.Clear( ) ;
    else
    if ( listdelete.SelectedIndex != -1 )
    listdelete.Items.Clear( ) ;
  }
}

The SelectedIndex property returns –1 if no item is currently selected. If any item is selected, the condition becomes true and the list box gets cleared.

The following figure shows our application at work. The list boxes seem to have trapped a few files being changed.

Type Effect
HOLDLOCK Hold a shared lock until completion of the transaction instead of releasing the lock as soon as the required table, row, or data page is no longer required. HOLDLOCK is equivalent to SERIALIZABLE.
NOLOCK Do not issue shared locks and do not honor exclusive locks. When this option is in effect, it is possible to read an uncommitted transaction or a set of pages that are rolled back in the middle of a read. Dirty reads are possible. Only applies to the SELECT statement.
PAGLOCK Use page locks where a single table lock would usually be taken.
READCOMMITTED Perform a scan with the same locking semantics as a transaction running at the READ COMMITTED isolation level. By default, SQL Server 2000 operates at this isolation level.
READPAST Skip locked rows. This option causes a transaction to skip rows locked by other transactions that would ordinarily appear in the result set, rather than block the transaction waiting for the other transactions to release their locks on these rows. The READPAST lock hint applies only to transactions operating at READ COMMITTED isolation and will read only past row-level locks. Applies only to the SELECT statement.
READUNCOMMITTED Equivalent to NOLOCK.

REPEATABLEREAD

Perform a scan with the same locking semantics as a transaction running at the REPEATABLE READ isolation level.
ROWLOCK Use row-level locks instead of the coarser-grained page- and table-level locks.
SERIALIZABLE Perform a scan with the same locking semantics as a transaction running at the SERIALIZABLE isolation level. Equivalent to HOLDLOCK.
TABLOCK Use a table lock instead of the finer-grained row- or page-level locks. SQL Server holds this lock until the end of the statement. However, if you also specify HOLDLOCK, the lock is held until the end of the transaction.
TABLOCKX Use an exclusive lock on a table. This lock prevents others from reading or updating the table and is held until the end of the statement or transaction.
UPDLOCK Use update locks instead of shared locks while reading a table, and hold locks until the end of the statement or transaction. UPDLOCK has the advantage of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it.
XLOCK Use an exclusive lock that will be held until the end of the transaction on all data processed by the statement. This lock can be specified with either PAGLOCK or TABLOCK, in which case the exclusive lock applies to the appropriate level of granularity

Yashavant Kanetkar, one of the first Express Computer columnists, is an established software expert, speaker and author with several best-sellers to his credit, including titles like “Let Us C” and the “Fundas” series. Contact him at kanetkar@dcubesoft.com
<Back to top>


© Copyright 2003: Indian Express Group (Mumbai, India). All rights reserved throughout the world. This entire site is compiled in
Mumbai by The Business Publications Division of the Indian Express Group of Newspapers.
Please contact our Webmaster for any queries on this site.