Click here to Skip to main content
Click here to Skip to main content

C#: Application to Watch a File or Directory using FileSystem Watcher

, 30 May 2008
Rate this:
Please Sign up or sign in to vote.
This article describesthe usage of the FileSystemWatcher object to watch changes to a file or a directory in C#

FileChangeNotifierV2.JPG

Introduction

In this article I describe the usage of the FileSystemWatcher object provided by VS 2008 (note: This object is same as the one in VS 2005), using C#. The application created here can be used to monitor any file or directory on your system. The generated change list contains notifications for creation, deletion, update or renaming of the file/directory content.

Background

The FileSystemWatcher object provided by .Net is a useful way to monitor a file system. Its definition is contained in the System.IO namespace. This object contains fields to mark which file or directory is to be monitored. Additionally the FileSystemWatcher object allows you to monitor a certain type of files in a directory using wildcards (eg. *.txt).

Using the code

A FileSystemWatcher instance can be created as follows using the new keyword:
m_Watcher = new System.IO.FileSystemWatcher(); 

Then we need to assign it a path and a filter to tell the object where to keep looking.

The line below tells the watcher that it has to keep looking at the path entered in the txtFile textBox. The '\\' characters at the end are to make sure that the path has a directory name. Orelse there will be a problem in case the user enters something like "C:" in the text box.

m_Watcher.Path = txtFile.Text + "\\"; 

Next we need to tell the watcher what all to look at.

The line below tells the watcher what files it is supposed to watch.
m_Watcher.Filter = strFilter;  

The value formats of strFilter and their meanings are as follows:

*.* - Watch all files in the Path
*.ext - Watch files with the extension ext
name.ext - Watch a particular file name.ext

Note that the file name.ext may not exist when the watcher begins watching. But as the file is created/moved to the Path directory, the watcher starts watching the file thereon.

Next we need to tell the watcher what to look for.

The following line does exactly that using various flags, each one describing a certain type of attribute of the file system.

m_Watcher.NotifyFilter = NotifyFilters.LastAccess | 
                         NotifyFilters.LastWrite | 
                         NotifyFilters.FileName | 
                         NotifyFilters.DirectoryName;

We can also tell the watcher to watch for changes to the sub-folders of the directory we specify in the Path by doing the following.

m_Watcher.IncludeSubdirectories = true; 

Next we need to describe what needs to be done when one of these attributes gets altered.

This is done by assigning different event handlers to different activities. In the present application we have used the same event handler for creation, change and deletion. This is done because we just need to log these changes the same way, and the change name is fetched from the argument in the event handler.

m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);

Note that Renamed activity has a different handler. This is because it has a different signature for its event handler. The signatures of both the handlers are as follows.

void OnChanged(object sender, FileSystemEventArgs e)
void OnRenamed(object sender, RenamedEventArgs e)

The change type in both cases can be fetched from the e argument as e.ChangeType

Lastly, we need to tell the watcher to do its job - Watch It!!!

This is done by enabling the watcher to raise events. This is done by the following line.

m_Watcher.EnableRaisingEvents = true;

Once this is done, the watcher keeps watching the assigned file/files or folders and appropriate events will be raised for their respective activities.

Points of Interest

Once the FileSystemWatcher is set to watch a file or folder, it will keep monitoring it till the end of the application. Setting the m_Watcher value to null will not stop it from monitoring. To stop the watcher while the application is still running, we need to stop it from raising events. This is done as follows.

m_Watcher.EnableRaisingEvents = false;

The current version of this application does not work for networked drives or folders shared over the network. I will post the code with this functionality in due time.

History

Version 1.0.0.0 uploaded on 05/31/2008
Version 1.0.0.1 uploaded on 06/01/2008

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Prashant K Singh
Team Leader Fx Labs Studios
India India
I work as a Lead Game Programmer at FxLabs Studios, an India based 3D desktop game development firm.
 
I have been a software engineer for 4 years and have worked in technologies like ASP .Net, VB .Net, C#, C/C++ etc.
 
Out of all this, C++ is my favorite and I am continually amazed at the versatility of STL.
 
My hobbies include Coding and Analyzing People Behavior... Smile | :)

Comments and Discussions

 
QuestionHow to extend this application for folder double click Pinmemberboneykalari28-Jun-14 0:22 
AnswerRe: How to extend this application for folder double click PinmemberMember 1038982127-Jul-14 13:09 
QuestionMonitoring connected device Folder Directory Pinmemberalanplacko18-Apr-14 9:37 
Questionwhat's new PinmemberOwen Gunter17-Mar-14 5:29 
QuestionAwsome app! PinmemberGustavo Carmellino11-Sep-13 18:37 
QuestionNot able to watch multiple files [modified] PinmemberAsutosha18-Jun-13 2:33 
QuestionWatcher.Create event always throw system.IO error PinmemberMurtuza A20-May-13 2:52 
QuestionGrate App PinmemberMember 386387210-May-13 19:04 
QuestionThe process cannot access the file -- because it is being used by another process PinmemberHamed Ali4-Mar-13 15:34 
SuggestionFileSystemWatcher PinmemberVijayKumar Parvathaneni7-Jan-13 23:07 
QuestionAny way to retrieve the process who trigged that action ? PinmemberMazen el Senih1-Nov-12 7:52 
QuestionThank you PinmemberMember 951444914-Oct-12 23:06 
QuestionHow to implement the same application in MFC PinmemberMember 927486411-Sep-12 18:49 
Questionhow to get file changes Pinmembersher_ali15-May-12 8:30 
GeneralMy vote of 5 PinmemberDFriday1328-Feb-12 10:18 
GeneralMy vote of 5 Pinmembermanoj kumar choubey15-Feb-12 23:24 
QuestionDirectory is not showing PinmemberAnkita Mali6-Jan-12 18:14 
GeneralMy vote of 1 PinmemberWerner van Deventer8-Oct-11 5:43 
Question[My vote of 1] ARE YOU KIDDING ME?! PinmemberSeishin#6-Oct-11 22:19 
AnswerRe: [My vote of 1] ARE YOU KIDDING ME?! PinmemberRohit Dubey from Hyderabad11-Jan-12 13:26 
SuggestionRe: [My vote of 1] ARE YOU KIDDING ME?! PinmemberMember 821039916-Jun-12 0:55 
AnswerRe: [My vote of 1] ARE YOU KIDDING ME?! PinmemberPrashant K Singh22-Oct-13 4:26 
GeneralGreat application! PinmemberSan4Ramyam7-Jun-11 22:02 
GeneralPlease help me Pinmembertranquocvietdanang2-Aug-10 22:01 
Questionhow to watching two folders? or more? Pinmemberyuyejian12-Jun-10 22:36 
AnswerRe: how to watching two folders? or more? PinmemberPrinuAji22-Jun-11 5:54 
GeneralI am not able to show the results. Pinmemberashu_himt23-Mar-10 7:16 
GeneralVote 5/5 Pinmemberanhduc.bkhn10-Oct-09 0:44 
GeneralMy vote of 1 PinmemberFelix Alcala2-Feb-09 12:58 
QuestionRe: My vote of 1 PinmemberPrashant K Singh15-Feb-09 0:53 
GeneralRe: My vote of 1 PinmemberMrJoe0128-Aug-09 0:10 
SuggestionRe: My vote of 1 PinmemberBo Alexander19-Jul-11 9:16 
GeneralHandling OnDelete & OnRename Pinmembermahone9-Dec-08 4:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 31 May 2008
Article Copyright 2008 by Prashant K Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid