Getting the notification in changes in File system with the help of FileSystemWatcher

Hi,

Yesterday I was playing around with some directories and a requirement came in where by I had to keep watch on the changes in the directory structure. My requirement was to update user as soon a there was a change in a file in the given directory.

I first thought of many ways to do it. By the end I found it was pretty easy to be done. We have to use the FileSystemWatcher class in the System.IO to get the job done.

Lets say we want a notification to be there when there is a change the D drive (D:\). If you want to also make the notification for sub directories then we need to set the IncludeSubdirectories to true. Here is a small code on how to use the component.

FileSystemWatcher watchFiles = new FileSystemWatcher(@"d:\\");

watchFiles.IncludeSubdirectories = true;

string dtCur = DateTime.Now.ToLongTimeString();

watchFiles.Changed += delegate(object sender, FileSystemEventArgs e)

                          {

                                     string file = Path.GetFileName(e.FullPath);

                                     string dir = Path.GetDirectoryName(e.FullPath);

                                     if (dtCur != DateTime.Now.ToLongTimeString())

                                     {

                                         // Do something here

                                     }

                            };

watchFiles.EnableRaisingEvents = true;

The last line is very important as it will start raising the event from that point only.

Thanks
Vikram

P.S. You can use the code to see all the changes in the temp file in local drive by changing the path to “C:\\”. This will show you on how much of work goes on even when you are doing nothing :-).


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia