.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Melody Anderson
Eminent IT

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Monitoring file system using FileSystemWatcher

Posted By:Hiren Soni       Posted Date: August 02, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

this article will show you how you can monitor file system using Filesystemwatcher like file created,deleted,changed,renamed

You can monitor the File system using the System.IO.FileSystemWatcher class. And you can handle the events like created, changed, deleted, and renamed.


Some important properties of FileSystemWatcher class




You can set the path which you want to monitor.





You can filter the files.

You can specify which files you want to monitor.

If you want to monitor all files you can use assign by "*.*";





It takes Boolean value.  You want to monitor only a specified path or you want to monitor all the subdirectories and files which is specified by path.





It takes Boolean value. It enables the raising events. By defaults it is false. You want to handle event on file system changes, you must set this property to true.








Let we see the code snippet:


using System.IO;


       private void Form1_Load(object sender, EventArgs e)


            FileSystemWatcher fsw = new FileSystemWatcher();

            fsw.Path = "c:\\temp\\";

            fsw.EnableRaisingEvents = true;

            fsw.Filter = "*.*";

            fsw.IncludeSubdirectories = true;

            fsw.Created += new FileSystemEventHandler(file_handler_function);

            fsw.Changed += new FileSystemEventHandler(file_handler_function);

            fsw.Deleted += new FileSystemEventHandler(file_handler_function);

            fsw.Renamed += new RenamedEventHandler(file_rename_handler_function);


        private void file_rename_handler_function(object sender, RenamedEventArgs e)



            Console.WriteLine("File Name is changed from " + e.OldFullPath + " to  " + e.FullPath);




        private void file_handler_function( object sender, FileSystemEventArgs e)


            if (e.ChangeType == WatcherChangeTypes.Created)


                MessageBox.Show("New file created : " + e.FullPath);


            else if (e.ChangeType == WatcherChangeTypes.Deleted)


                MessageBox.Show("File is deleted : " + e.FullPath);


            else if (e.ChangeType == WatcherChangeTypes.Changed)


                MessageBox.Show("File modified : " + e.FullPath);



 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend