A 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.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This 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.
Creating 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.
File monitoring using FileSystemWatcherLearn 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) |
||||
|
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 FileSystemWatcherStart 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. ![]() 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. ![]() 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:
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:
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. |
|||||
private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e) |
private void btnMonitor_Click(object sender, EventArgs e) |
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
Rate this tutorial
Current Commentsjust what i was looking for !
thanks for this sample application , i needed this to import some files to SQL Server
I've notice that when I just save a file that the "Changed" event is triggered twice. Any ideas why?
Aside from the change in content, there is a change in attributes (Last Modified date).
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.
Nice stuff.Greate help in the application I was developing.
great work...easy to understand..keep posting these types of informative and useful articles.
just as info...when i created the solution on network it was giving me an security exception error
Any possibility of triggering the Change event only once instead of twice
Here i want to rename folder by c#.net in asp.net 2.0
is there any solution for it?
thank.
Very nice simple application. Does filewatcher know who is making changes, deletes... to the particular file?
Any thanks.
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
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);
}
}
}
Hi all!
I am developing program like this, but i need to detect user who made some changes.Any ideas?
Well Done.
I took a clear idea of FileSystemWatcher.
Thank you very much
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
Great job dude. thank you very much. this sample application will help me a lot.
Nice job! This was exactly what I was looking for...
really nice job,but can we know what is the process that changed or deleted a file...
EXCELENTE MUCHAS GRACIAS.
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?
If you are shahid riaz, former employee of Streaming Networks then contact me, i will explain the details what you required.
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?
how to align a third party exe or a pop up window
on a screen in c#
If the event Changed is threw a text file:
How I can see new the change????
(Before and After)
Thanks
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)
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
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)
{
}
}
}
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..,
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
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.
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
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.
Any possibility of triggering the Change event only once instead of twice
http://technews.comli.com
Any possibility of triggering the Change event only once instead of twice
http://technews.comli.com
Any possibility of triggering the Change event only once instead of twice
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!
thanks a lot.
very good tutorial...
i am having trouble with this functionality on a networked drive too, it's a nice bit of code for use locally
it's a nice bit of code for use locally but trying to get it going for a folder on server is a nightmare!
thank you sir for your wonderful code...
i really enjoyed it..
now i will get good sleep at night..
Related Tutorials
Related Source Code
C# Job SearchFrom 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.