Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

File monitoring using FileSystemWatcher

Learn how to create your own file and folder monitoring application in C# using the FileSystemWatcher object. A sample application will be built in .NET 2.0 which can be used to monitor files, folders or drives.

On Tuesday, March 28th 2006 at 04:48 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.4 with 34 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (C# 2005)

Wondering what's cranking your harddisk so hard? Using C# (.NET 1.1 or 2.0, whichever you prefer) and the FileSystemWatcher object you can easily build yourself a file monitoring application. You'll be able to see what files are being created, changed, renamed or deleted.
First we're going to write a few lines of code to quickly see how the FileSystemWatcher object operates. Then after we get the hang of it, we'll be building a simple Windows application that monitors a folder (or drive) for changes and writes the events to a log.

Working with FileSystemWatcher

Start by creating a Windows Application in Visual Studio 2005. Note that Visual Studio 2003 and .NET 1.1 can also be used for this project, but the one attached to this tutorial is created in Visual Studio 2005 and .NET 2.0, thus you won't be able to open it using an earlier version.

Browse the toolbox for the FileSystemWatcher object, and drag it to the form.

FileSystemWatcher

Name it fileWatcher and since you're in the Properties window let's check the properties:
First, make sure the EnableRaisingEvents property is set to True otherwise the monitoring will not be enabled. The Filter property should either be set to *.* or to an empty string. This assures that we're not filtering any files, and we want to monitor each and every one of them.
Since we want to see some action, let's include subdirectories in the file monitoring, so set IncludeSubdirectories to True.
The NotifyFilter property should be left with its default value - FileName, DirectoryName, LastWrite.
As for the Path property, you'll probably want to enter C:\ since it's such a frequently accessed drive.

Now switch to the events view and you can see the 4 events of the FileSystemWatcher object. As their name implies, the events are being fired when a file is changed, created, deleted or renamed.

Events View

Doubleclick the first field (Changed) and you'll get to the event handler fileWatcher_Created(). Since this event is being fired when a file is changed, we want to be made aware of that. Thus, replace the event handler with the following code:

private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
MessageBox.Show(e.ChangeType + ": " + e.FullPath);
}


You can compile your application now. Once something is changed in C:\ a message box will popup showing the path to the file that suffered the change. It normally shouldn't take very long before this type of event occurs. You can try modifying a file on C:\ yourself, to see the event being fired.

You can do the same thing for the other events (Created, Deleted and Renamed). Double click them to get to the event handler, and paste the same MessageBox.Show() line.
The Rename event has two more properties unlike the other events: OldFullPath and OldName, which show the path / name of the file before it was renamed:

private void fileWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
MessageBox.Show("Renamed from " + e.OldFullPath + " to " + e.FullPath);
}



Creating a file monitoring application

Now that you know how to use FileSystemWatcher to monitor a folder or a drive, let's create a Windows application where we can offer the user greater flexibility on monitoring his files.
Start a Windows application project in your Visual Studio 2005 evironment. Create a form similar to the one below. There's a textbox named txtPath where the default value is C:\, there's another one below named txtFilter that has the default value set to *.* and a checkbox chkSubdirectories that you'll want to keep as checked by default.
Then add two buttons (btnMonitor and btnStop) and a multiline textbox that we're going to use as a log. You might have guessed its name: txtLog.


File Monitor Form

Now that we have the form ready, we can proceed to coding it.

After you've added the FileSystemWatcher object to the project, and renamed it to fileWatcher, in the Properties window set the EnableRaisingEvents property to False, since we don't want it to start monitoring files right after we fire up the application.
Now switch to the events view and double click the field next to each of the 4 events to create the handlers. Use the following code for the event handlers:

private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
// Write details to the log
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
// Put the focus on the log textbox
txtLog.Focus();
// Put the cursor at the end of the text
txtLog.Select(txtLog.TextLength, 0);
// Scroll to the bottom of the textbox
txtLog.ScrollToCaret();
}

private void fileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void fileWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void fileWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
txtLog.Text += e.ChangeType + ": " + e.OldFullPath + " renamed to " + e.FullPath;
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}


In each event handler, only one line is used for putting the text in the textbox. The other three lines are necessary for scrolling to the bottom of the textbox after the text was added. This ensures the latest log lines are visible.

What's left to do is turn this thing on... and off. So double click the btnMonitor and btnStop buttons to get to their event handler. There use the appropriate code for turning the monitoring on and off:

private void btnMonitor_Click(object sender, EventArgs e)
{
fileWatcher.Path = @txtPath.Text;
fileWatcher.Filter = txtFilter.Text;
fileWatcher.IncludeSubdirectories = chkSubdirectories.Checked;
fileWatcher.EnableRaisingEvents = true;
}

private void btnStop_Click(object sender, EventArgs e)
{
fileWatcher.EnableRaisingEvents = false;
}


That's it.
Compile your new file monitoring application and after a few seconds of using your computer, you should see a log screen similar to the following:

File and Folder Monitoring

By specifying a filter you can monitor only files with a certain extension, or even a single file. For example if you specify index.dat in the filter textbox, only this file will be monitored.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by paul on Friday, June 2nd 2006 at 05:41 AM

just what i was looking for !
thanks for this sample application , i needed this to import some files to SQL Server

by Forch on Sunday, June 4th 2006 at 06:33 PM

I've notice that when I just save a file that the "Changed" event is triggered twice. Any ideas why?

by Andrei Pociu on Monday, June 5th 2006 at 02:15 AM

Aside from the change in content, there is a change in attributes (Last Modified date).

by Chris on Monday, July 31st 2006 at 03:32 PM

Another useful application. Well done, your\'re doing a great job, I find those sample applications very useful to learn how to do various development tasks.

by Nicholas on Friday, March 9th 2007 at 05:00 AM

Nice stuff.Greate help in the application I was developing.

by Romie on Tuesday, August 28th 2007 at 04:26 PM

great work...easy to understand..keep posting these types of informative and useful articles.

by Romie on Tuesday, August 28th 2007 at 04:28 PM

just as info...when i created the solution on network it was giving me an security exception error

by Daniel on Tuesday, May 20th 2008 at 09:11 AM

Any possibility of triggering the Change event only once instead of twice

by Anil Desai on Thursday, June 19th 2008 at 09:30 AM

Here i want to rename folder by c#.net in asp.net 2.0

is there any solution for it?

thank.

by khautinh on Thursday, June 26th 2008 at 01:15 PM

Very nice simple application. Does filewatcher know who is making changes, deletes... to the particular file?

Any thanks.

by en on Tuesday, July 15th 2008 at 04:20 AM

Hi Andrei Pociu,

I'm a newbie programmer can you teach me how to determine what process created the file or what program read, modified and deleted the file

Thanks so much and more power

by Changming Zhang on Sunday, July 27th 2008 at 08:47 PM

Excellent!

I got a similiar program below and it runs well in console. But there is no events generated after I delete or create a folder under the dir. defined in the code. It'll be appreciated if anyone can tell me why. Thanks, Changming
Here is the code;


namespace monitorChange
{
class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\";

// Register for events
watcher.Created = new FileSystemEventHandler(watcher_Changed);
watcher.Deleted = new FileSystemEventHandler(watcher_Changed);

// Start Watching
watcher.EnableRaisingEvents=true;
}

// Event Handler
static void watcher_Changed (object sender, FileSystemEventArgs e)
{
Console.WriteLine("Directory changed({0}): {1}", e.ChangeType, e.FullPath);

//Console.WriteLine("File: " e.ChangeType e.FullPath);
}
}

}

by Atilla on Friday, September 19th 2008 at 05:48 AM

Hi all!
I am developing program like this, but i need to detect user who made some changes.Any ideas?

by Sameetha on Friday, November 14th 2008 at 12:15 AM


Well Done.
I took a clear idea of FileSystemWatcher.
Thank you very much

by JJ on Friday, February 6th 2009 at 03:44 AM

I was looking for a similar program, if this is on a shared folder, would it be possible to show the name of the person who modified or deleted the file

by sharif on Wednesday, March 25th 2009 at 01:39 AM

Great job dude. thank you very much. this sample application will help me a lot.

by Leon on Friday, April 24th 2009 at 06:52 AM

Nice job! This was exactly what I was looking for...

by lost_in_code on Tuesday, May 5th 2009 at 08:04 AM

really nice job,but can we know what is the process that changed or deleted a file...

by CLAUDIO on Thursday, May 7th 2009 at 10:57 AM

EXCELENTE MUCHAS GRACIAS.

by Shahid Riaz on Friday, May 22nd 2009 at 09:27 AM

I like this article..
I am alreadi working on a project which needs to tack that how many files have been copied to the Watching fodler. I used the Created event, so whenever a file is created in the watching fodler I start further proccessing on that newly created file. This works well with small file. But when I tried to copy some large file (i.e. size in gb) then i got some problem which is that Created event triggerd immediately as soon as the file is created, and my code starts to work on that newly created file. But in case of large file the contents of the file is not written in the file yet and so I get exception in my code. Basically I need to know that how to make sure in Created event of the Filewatcher that the file which is just created is completely copied?

by Muhammad Imran on Friday, July 10th 2009 at 01:10 AM

If you are shahid riaz, former employee of Streaming Networks then contact me, i will explain the details what you required.

by Ahriman on Wednesday, August 26th 2009 at 06:55 PM

Thanks heaps for this tutorial. It works perfectly against my local hard drive, but it doesn't pick up any events at all for a mapped network drive. Is there any way to get this functionality into this application?

by sujith on Saturday, September 12th 2009 at 01:19 AM

how to align a third party exe or a pop up window
on a screen in c#

by Moises on Wednesday, February 24th 2010 at 11:02 AM

If the event Changed is threw a text file:
How I can see new the change????
(Before and After)
Thanks

by ariezz on Thursday, June 24th 2010 at 06:45 AM

i have to use FileSystemWatcher class in asp.net plz help me how to use??? is there any object we can use for FileSystemWatcher in asp.net(c#)(VS2008)

by Naresh on Saturday, July 17th 2010 at 10:47 PM

am searching for the same kind of program..,pls could you able to help me in retrieving deleted files and to dump the RAM memory

by Jig on Friday, August 27th 2010 at 03:43 PM

Great Job.

Instead of getting changed file update in the text box, can I setup as email?

According to my script, I get email when I click on Monitor button but not when the file data actually get changed.....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace FileMonitor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
txtLog.Text = e.ChangeType ": " e.FullPath "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void fileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
txtLog.Text = e.ChangeType ": " e.FullPath "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void fileWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
txtLog.Text = e.ChangeType ": " e.FullPath "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void fileWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
txtLog.Text = e.ChangeType ": " e.OldFullPath " renamed to " e.FullPath;
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
}

private void btnMonitor_Click(object sender, System.EventArgs e)

{
btnStop.Enabled = true;
fileWatcher.EnableRaisingEvents = true;
MailMessage msg = new MailMessage("xxx@gmail.com", "xxx@gmail.com");
msg.Subject = "Email Test";
msg.Body = "Submitted By: xxx";
msg.Body = "Alert";
msg.From = "xxx@gmail.com";
msg.To = "xxx@gmail.com";
SmtpClient SmtpMail = new SmtpClient("localhost");
SmtpMail.Host = "smtp.gmail.com";
SmtpMail.Credentials = CredentialCache.DefaultNetworkCredentials;
SmtpMail.Port = 576;
SmtpMail.Timeout = 50000;
SmtpMail.EnableSsl = true;
SmtpMail.Credentials = new System.Net.NetworkCredential("username", "password");

try
{
SmtpMail.Send(msg);
}

catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}


btnMonitor.Enabled = false;

}

private void btnStop_Click(object sender, EventArgs e)

{
btnMonitor.Enabled = true;
btnStop.Enabled = false;
fileWatcher.EnableRaisingEvents = false;
}

private void btnFolderTree_Click(object sender, EventArgs e)
{
DialogResult result = ofdOpenFile.ShowDialog();
if (result == DialogResult.OK)
{
txtPath.Text = Path.GetFullPath(ofdOpenFile.FileName);
}

}

private void Form1_Load(object sender, EventArgs e)
{

}
}
}

by naresh on Wednesday, September 8th 2010 at 05:33 AM

hi jig..,
just write a function for sending mail and call them from tha file watcher function after writting to the log file and pass the content of the logfile as arguments to mail function..,

by Shahid Riaz Bhatti on Friday, February 25th 2011 at 08:31 AM

Well, In this post I have asked a question that how to handle large file in case of Filwwatcher and atthat time i didnt get reply, and anyhow i fugured it out that how to handle large file.
I have shared my solution on the following link. It might help someone else:

http://www.shahidriaz.com/post/2009/05/25/FileSystemWatcher.aspx

by credit cards to build credit on Monday, December 12th 2011 at 05:30 AM

Use System.Windows.Forms.Cursor.Position to get the cursor position in screen coordinates.I admire the important information you offer within your content. I'll bookmark your web site and have my kids examine up the following typically.

by Waclawa on Saturday, January 14th 2012 at 01:58 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by gdpoker on Sunday, January 22nd 2012 at 10:58 AM

Simply want to say your article is as amazing. The clearness in your post is just spectacular and i can assume you're an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.

by Amy on Wednesday, February 29th 2012 at 04:57 AM

Any possibility of triggering the Change event only once instead of twice
http://technews.comli.com

by Amy on Wednesday, February 29th 2012 at 04:57 AM

Any possibility of triggering the Change event only once instead of twice
http://technews.comli.com

by Tech News on Wednesday, February 29th 2012 at 04:58 AM

Any possibility of triggering the Change event only once instead of twice

by greg wallis on Thursday, March 8th 2012 at 09:10 AM

i am having trouble with this functionality on a networked drive too, it's a nice bit of code for use locally but trying to get it going for a folder on server is a nightmare!

by Sankha on Tuesday, August 14th 2012 at 01:35 AM

thanks a lot.
very good tutorial...

by video conferencing applications on Tuesday, October 2nd 2012 at 02:49 AM

i am having trouble with this functionality on a networked drive too, it's a nice bit of code for use locally

by wise freeze dried food company on Thursday, October 25th 2012 at 02:20 AM

it's a nice bit of code for use locally but trying to get it going for a folder on server is a nightmare!

by syed on Saturday, November 3rd 2012 at 08:50 AM

thank you sir for your wonderful code...
i really enjoyed it..
now i will get good sleep at night..

by ammarany on Tuesday, March 4th 2014 at 08:34 AM

Awesome Artical Really i have searching this type of valuable information From a lot of days i found satisfaction when Read your blog Thanks for giving this type blog and also please Read link bvba Woodstone which provide information server monitoring software


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources