Click here to Skip to main content
14,920,432 members
Articles / Desktop Programming / Windows Forms
Posted 30 May 2008


107 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
4.75/5 (64 votes)
30 May 2008CPOL3 min read
This article describesthe usage of the FileSystemWatcher object to watch changes to a file or a directory in C#



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.


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 | 

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.


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


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

QuestionWhich file is being accessed by which application in Windows Pin
hardiik21-Jun-18 4:17
Memberhardiik21-Jun-18 4:17 
QuestionGood Approach ... Pin
RamalingamSrini20-Oct-17 2:40
MemberRamalingamSrini20-Oct-17 2:40 
QuestionSpecific Files Pin
Allan Joshua23-Apr-17 20:02
MemberAllan Joshua23-Apr-17 20:02 
Praisevery nice Pin
shinn_3322-Oct-16 11:44
Membershinn_3322-Oct-16 11:44 
QuestionWindows app file upload utility Pin
Member 105436873-Jan-16 22:08
professionalMember 105436873-Jan-16 22:08 
QuestionApplication to Watch a File or Directory using FileSystem Watcher Pin
Mr. PALANI M20-Oct-15 4:35
professionalMr. PALANI M20-Oct-15 4:35 
Questionproblem with network ext4 parttitions Pin
user_ric1-Oct-15 0:44
Memberuser_ric1-Oct-15 0:44 
QuestionHELP. Copying several files only triggers 1 onCreated event Pin
3sley15-Sep-15 4:42
Member3sley15-Sep-15 4:42 
AnswerRe: HELP. Copying several files only triggers 1 onCreated event Pin
3sley17-Sep-15 3:49
Member3sley17-Sep-15 3:49 
Buggrated but ........................... Pin
anssary201025-Apr-15 8:20
Memberanssary201025-Apr-15 8:20 
QuestionThanks Pin
rcadeng8-Apr-15 4:52
Memberrcadeng8-Apr-15 4:52 
General-Application-to-Watch-a-File-or-Directory Pin
Aditya Chauhan7-Apr-15 20:45
MemberAditya Chauhan7-Apr-15 20:45 
QuestionUser name Pin
Manu Prasad3-Apr-15 22:41
MemberManu Prasad3-Apr-15 22:41 
QuestionHI Pin
Member 1146091620-Feb-15 23:21
MemberMember 1146091620-Feb-15 23:21 
QuestionIssue: Bug -> Redesign Pin
bhamper6-Feb-15 12:29
Memberbhamper6-Feb-15 12:29 
QuestionHow to extend this application for folder double click Pin
boneykalari28-Jun-14 0:22
Memberboneykalari28-Jun-14 0:22 
AnswerRe: How to extend this application for folder double click Pin
Kirk 1038982127-Jul-14 13:09
MemberKirk 1038982127-Jul-14 13:09 
QuestionMonitoring connected device Folder Directory Pin
alanplacko18-Apr-14 9:37
Memberalanplacko18-Apr-14 9:37 
Questionwhat's new Pin
Owen Gunter17-Mar-14 5:29
MemberOwen Gunter17-Mar-14 5:29 
QuestionAwsome app! Pin
Gustavo Carmellino11-Sep-13 18:37
MemberGustavo Carmellino11-Sep-13 18:37 
QuestionNot able to watch multiple files Pin
Asutosha18-Jun-13 2:33
professionalAsutosha18-Jun-13 2:33 
QuestionWatcher.Create event always throw system.IO error Pin
Murtuza A20-May-13 2:52
MemberMurtuza A20-May-13 2:52 
QuestionGrate App Pin
Member 386387210-May-13 19:04
MemberMember 386387210-May-13 19:04 
QuestionThe process cannot access the file -- because it is being used by another process Pin
Hamed Ali4-Mar-13 15:34
MemberHamed Ali4-Mar-13 15:34 
SuggestionFileSystemWatcher Pin
VijayKumar Parvathaneni7-Jan-13 23:07
MemberVijayKumar Parvathaneni7-Jan-13 23:07 

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

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