ARTICLE

Email notification of FileSystem changes in VB.NET

Posted by Sateesh Arveti Articles | VB.NET Windows Service December 27, 2006
This article tells us how to create a windows service to get notifiactions of filesystem changes remotely.
Download Files:
 
Reader Level:

In every system, there may be some important files to make system work properly. Suppose, you shared such important folder and you went to some other place. Suddenly, your friend calls you and tell that system is not working properly. The most possible reason may be he deleted some important files. How can you know, which files he deleted and at what time. You are away from your system, so you can't even find files which are deleted. So to overcome such situation, I created an application which will send a mail to you, whenever any important files are deleted, renamed or its contents changed. The message sent to you, will clearly tell files update status.

I developed this service in VB.NET in VS 2003.

Create a Windows Service in VB.NET and name it as filesystemwatcher as shown below:

 

Add reference to System.Web.dll by going to Solution Explorer, clicking on References(->Add Reference) as shown below:

 

Next go to code window, find "Service1" and replace with filesystemwatcher in all places. Next go to design view, select properties and set Autolog  to false and ServiceName to filesystemwatcher.

Next keep a Timer control by dragging it from Components tab of Toolbar.

Next add Installer, by right clicking on design window as shown in figure:

Next go to properties of ServiceInstaller1, and set StartType to Automatic and DisplayName and ServiceName to filesystemwatcher.

Next goto properties of ServiceProcessInstaller1, and set Account to LocalSystem.

Next goto Timer Properties window, and set enabled to true, Interval to 60000.(1 Minute).

Next goto code window and add this statements there:

Imports System.IO

Imports System.Web

 

Paste the below code in the timer1_Elapsed event of the Timer control:

 

Dim dir As New DirectoryInfo("c:\satish1")

 

Dim f As FileInfo

For Each f In dir.GetFiles()

    Dim diff As TimeSpan = (DateTime.Now - f.LastWriteTime)

 

    If diff.Hours = 0 AndAlso diff.Minutes <= 1 Then

            Dim message As New System.Web.Mail.MailMessage

            message.To = "xxx@yahoo.co.in"

            message.From = "FileSystemWatcher@ans.com"

            message.Subject = "File Contents Changed  " + f.FullName.ToString()

            message.Body = "The Following File Contents are Changed  " + Path.GetFileName

             (f.FullName.ToString()) + " of size " + f.Length.ToString() + " at " +

            DateTime.Now.ToLongTimeString() + " by " + System.Environment.UserName.ToString()

            System.Web.Mail.SmtpMail.Send(message)

    End If 'For Verification of message,we can use EventLog....                                  

Next f

 

The above code will send a mail, whenever a file content is changed in  c:\satish1 folder.

This code will check the specified folder for every minute and send a mail, if it contents are changed within that timespan.

Next go to OnStart event and paste this code:

Dim dirname As String = "c:\satish1"

'string dirname=@"c:\";   to monitor entire C: drive....

watch = New System.IO.FileSystemWatcher(dirname, "*.*")

AddHandler watch.Created, AddressOf Me.FileCreated

AddHandler watch.Deleted, AddressOf Me.FileDeleted

AddHandler watch.Renamed, AddressOf Me.FileRenamed

watch.IncludeSubdirectories = True

watch.EnableRaisingEvents = True

 

This will create a FileSystemWatcherobject for monitoring folder. I created 3 methods to handle create, delete and rename of a file. I specified that handlers in OnStart event.

Next paste this methods in code window:

Public Sub FileCreated(ByVal sender As Object, ByVal e1 As FileSystemEventArgs)

 

    Dim message As New System.Web.Mail.MailMessage

    message.To = "xxx@gmail.com"

    message.From = "FileSystemWatcher@ans.com"

    message.Subject = "File Created " + e1.FullPath.ToString()

    message.Body = "The Following File is  Created " + Path.GetFileName(e1.FullPath.ToString()) + " in " +

    Path.GetDirectoryName(e1.FullPath.ToString()) + " at " + DateTime.Now.ToLongTimeString() + " by " +

    System.Environment.UserName.ToString()

    System.Web.Mail.SmtpMail.Send(message)

End Sub 'FileCreated

 

Public Sub FileDeleted(ByVal sender As Object, ByVal e1 As FileSystemEventArgs)

 

    Dim message As New System.Web.Mail.MailMessage

    message.To = "xxx@gmail.com"

    message.From = "FileSystemWatcher@ans.com"

    message.Subject = "File Deleted " + e1.FullPath.ToString()

    message.Body = "The Following File is  Deleted " + Path.GetFileName(e1.FullPath.ToString()) + " in " +

    Path.GetDirectoryName(e1.FullPath.ToString()) + " at " + DateTime.Now.ToLongTimeString() + " by " +

    System.Environment.UserName.ToString()

    System.Web.Mail.SmtpMail.Send(message)

End Sub 'FileDeleted

 

Public Sub FileRenamed(ByVal sender As Object, ByVal e1 As RenamedEventArgs)

    Dim message As New System.Web.Mail.MailMessage

    message.To = "xxx@gmail.com"

    message.From = "FileSystemWatcher@ans.com"

    message.Subject = "File Renamed " + e1.OldFullPath.ToString()

    message.Body = "The Following file is Renamed from " + e1.OldName.ToString() + " " + "To " +

    e1.Name.ToString() + " in " + Path.GetFileName(e1.FullPath.ToString()) + " at " +

    DateTime.Now.ToLongTimeString() + " by " + System.Environment.UserName.ToString()

    System.Web.Mail.SmtpMail.Send(message)

End Sub 'FileRenamed

 

Change the name of folder according to your requirement in OnStart and in timer1_elapsed event.

Each method handle creation, deletion and rename of a file and send a mail to xxx@gmail.com with required information of file.

Next, paste this code in OnStop event:

watch.Dispose()

timer1.Enabled = False

 

Next build solution by pressing Ctrl+Shift+B. If build is succeeded, then go to command prompt of VS Tools.

Go to debug folder of your solution and type

InstallUtil filesystemwatcher.exe

If commit phase is succeeded, then type this to start service.

net start filesystemwatcher.

Change the folder contents, you specified and see whether a mail will come or not.

I hope this code will be useful to all. I am attaching code for further assistance.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/).

Login to add your contents and source code to this article
share this article :
post comment
 

Sateesh...Thanks for the great article. I am a newbie and is working perfectly. I have 2 questions Q1: This service works when I setup the service to look for local folder on my system..If I change the lookup folder to some shared drive on another system..the service is not getting started. What needs to be done here. Q2: In the email part it is working fine whenever a file is added or deleted or modified. But in the email it always gives my system name and my ID though it is changed at others system. I would like to see his system name and his ID. What needs to be done here. Pls advice and thanks in advance --Peter

Posted by Peter Nelson Aug 30, 2007

Thanks Sateesh. I'm a newbie in programming, and have been having a hard time to figure out where was the problem on other sample, that just didn't work for me. But yours, finally, worked!!!

Posted by guta guta Apr 09, 2007
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor