Programatically monitor directory for changes using c#

To check for changes to a directory i.e a new file or folder added to the directory or a file or folder deleted from the directory, we must use the filesystemwatcher class. This class allows us to raise events when changes occur to a directory. We create a new FileSystemWatcher object, specifying the directory in the Path property and register for the Created and Deleted events. The events are turned on by setting EnableRaisingEvents to true.

Example code:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\mydir";
 
// Register for events
watcher.Created += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
 
// Start Watching
watcher.EnableRaisingEvents = true;
 
// Event Handler
static void watcher_Changed(object sender,FileSystemEventArgs e)
{
	Console.WriteLine("Directory changed({0}): {1}",
		e.ChangeType,
		e.FullPath);
}
Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

 

 
eXTReMe Tracker