SIGN UP MEMBER LOGIN:    
ARTICLE

File System Watcher in C#

Posted by Suchit Khanna Articles | C# Language June 09, 2011
Here you will see how to use a File System Watcher in C#.
Reader Level:
Download Files:
 


In my current project I had to implement a utility that would monitor a given directory and notify the application so it could take certain actions based on these changes.

I ended up using the FileSystemWatcher class that is available from the .NET framework to monitor a directory.

Let us first see how this class works with a small console sample, where in we will monitor a directory. So take a dive and create a Console Application.

You will need to add:

using System.IO;

Next in the main function add the following lines of code:

FileSystemWatcher watcher = new FileSystemWatcher();

int index = Assembly.GetExecutingAssembly().Location.LastIndexOf("\\");

string _path = Assembly.GetExecutingAssembly().Location.Substring(0, index);

watcher.Path = _path;

watcher.EnableRaisingEvents = true;

watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
Console.WriteLine("FileSystemWatcher ready and listening to changes in :\n\n" + _path);"

The code above is self explanatory but let's dissect it for making it simpler:

int index = Assembly.GetExecutingAssembly().Location.LastIndexOf("\\");

string _path = Assembly.GetExecutingAssembly().Location.Substring(0, index);

watcher.Path = _path;

Here we set the path of the directory we want to monitor. In the first two lines of code we are getting the current working directory where our EXE is located and that we want the FileSystemWatcher instance in our sample to monitor.

Next, you can see with the help of intellisense that there are many events supported by the class; the ones we have subscribed to are:

 static void watcher_Renamed(object sender, RenamedEventArgs e)
  {
      Console.WriteLine(e.OldName + " is now: " + e.Name);
  }

  static void watcher_Changed(object sender, FileSystemEventArgs e)
  {
      Console.WriteLine(e.Name + " has changed");
  }

  static void watcher_Deleted(object sender, FileSystemEventArgs e)
  {
      Console.WriteLine(e.Name + " file has been deleted");
  }

  static void watcher_Created(object sender, FileSystemEventArgs e)
  {
      Console.WriteLine(e.Name + " file has been created.");
  }

There is nothing much to explain in the above event handlers, we are just displaying the names of the files affected with respect to each event handler.

Let us go ahead and see how our simple and small sample works, press F5 or Ctrl+F5 to run the exe from Visual Studio then go to the working directory (…\Debug\bin) in our case.

FSWatcher1.gif

Now we are going to create a new .txt file in the directory:

FSWatcher2.gif


FSWatcher3.gif

The corresponding event (created is triggered) and the output can be seen in console:

FSWatcher4.gif

Next go ahead and change the file name to some other name, as I did to empty.txt and here is the output as seen in the console:

FSWatcher5.gif

FSWatcher6.gif

Let us add a sample test to our empty.txt file by opening it:

FSWatcher7.gif

Now save the file (Ctrl + S or from File menu) and see the console output:

FSWatcher8.gif

And last but not the least, let us delete the file (empty.txt) and see the corresponding event being triggered by FileSystemWatcher:

FSWatcher9.gif

Well this class can be used for building many useful utility applications as well as frameworks and, in the next article I will take you through a useful application that uses this class. Until then enjoy coding  .
 

Login to add your contents and source code to this article
share this article :
post comment
 

Hey..this is a very good article..on c#..this features is very cool..even i also dnt know..but now i know...g8..

Posted by Shirsendu Nandi Jun 09, 2011

Thanks Dinesh.

Posted by Suchit Khanna Jun 09, 2011

Very useful article....

Posted by Dinesh Beniwal Jun 09, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor