Click here to Skip to main content
15,867,141 members
Articles / Desktop Programming / Windows Forms
Article

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 449.7K   47.6K   108   51
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)


Written By
Program Manager Wipro Technologies
India India
I have a Bachelor's Degree in Electrical Engineering, class of 2004 and has been interested in software development since second grade (you read it right)

I have built and led highly efficient and performant teams from ground up and have been able a part of several Digitization and Cloud Transformation efforts for large enterprises.

Apart from software building, I also hold a keen interest in Photography, Travelling and tinkering with Arduino and Raspberry Pi

Comments and Discussions

 
QuestionWhich file is being accessed by which application in Windows Pin
hardiik21-Jun-18 4:17
hardiik21-Jun-18 4:17 
QuestionGood Approach ... Pin
RamalingamSrini20-Oct-17 2:40
RamalingamSrini20-Oct-17 2:40 
QuestionSpecific Files Pin
Allan Joshua23-Apr-17 20:02
Allan Joshua23-Apr-17 20:02 
Praisevery nice Pin
shinn_3322-Oct-16 11:44
shinn_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
user_ric1-Oct-15 0:44 
QuestionHELP. Copying several files only triggers 1 onCreated event Pin
3sley15-Sep-15 4:42
3sley15-Sep-15 4:42 
AnswerRe: HELP. Copying several files only triggers 1 onCreated event Pin
3sley17-Sep-15 3:49
3sley17-Sep-15 3:49 
Buggrated but ........................... Pin
anssary201025-Apr-15 8:20
anssary201025-Apr-15 8:20 
QuestionThanks Pin
rcadeng8-Apr-15 4:52
rcadeng8-Apr-15 4:52 
General-Application-to-Watch-a-File-or-Directory Pin
Aditya Chauhan7-Apr-15 20:45
Aditya Chauhan7-Apr-15 20:45 
QuestionUser name Pin
Manu Prasad3-Apr-15 22:41
Manu Prasad3-Apr-15 22:41 
QuestionHI Pin
Member 1146091620-Feb-15 23:21
Member 1146091620-Feb-15 23:21 
QuestionIssue: Bug -> Redesign Pin
bhamper6-Feb-15 12:29
bhamper6-Feb-15 12:29 
QuestionHow to extend this application for folder double click Pin
boneykalari28-Jun-14 0:22
boneykalari28-Jun-14 0:22 
Is it possible to create a c# background application, that monitors a specific folder. i.e If somebody double clicks a particular folder some alert message should be shown.
I am a system administrator (windows 7) and want to create a background service that invokes web cam when a folder is clicked. I have 3 Windows machines with .NET Framework installed and have full control over them.

I have tried basic event handlers that are watching for specific event like create, delete, rename, change etc.. but I didn't find anything for folder double click. My requirement is simple, i just wanted to know how to grab the folder double event in the application.
AnswerRe: How to extend this application for folder double click Pin
Kirk 1038982127-Jul-14 13:09
Kirk 1038982127-Jul-14 13:09 
QuestionMonitoring connected device Folder Directory Pin
alanplacko18-Apr-14 9:37
alanplacko18-Apr-14 9:37 
Questionwhat's new Pin
Owen Gunter17-Mar-14 5:29
Owen Gunter17-Mar-14 5:29 
QuestionAwsome app! Pin
Gustavo Carmellino11-Sep-13 18:37
Gustavo 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
Murtuza A20-May-13 2:52 
QuestionGrate App Pin
Member 386387210-May-13 19:04
Member 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
Hamed Ali4-Mar-13 15:34 
SuggestionFileSystemWatcher Pin
VijayKumar Parvathaneni7-Jan-13 23:07
VijayKumar 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.