Watching Folder Activity in VB.NET

Environment: PL/SQL on 64-bit Oracle9i Enterprise Edition version 9.2.0.1.0

Introduction

Have you ever wanted to write an application that constantly monitors a folder and raises events when there is any activity in that folder? In the good old days, using VB6 or an older version, you had to use Windows APIs to do something like this. It was not very simple and required lots of coding.

Microsoft .NET Framework has introduced classes such as System.IO and System.Diagnostics, which contain the FileSystemWatcher class that can raise events when a file is created/renamed/updated or deleted from the specified folder or any other activities.

In this article, we're going to learn how to implement the FileSystemWatcher class using Microsoft Visual Basic.Net. You will need the .NET framework installed, as well as Visual Studio.Net, if you want to experiment with the source code presented in this article.

Getting Started

Open Visual Studio .NET and create a new Windows Application Project. Call it WatchFolder and click OK.

Create a user interface as shown in the image below.

Add the following controls:

Control Type Description
txt_watchpath TextBox   For the folder path  
btn_startwatch Button Start watching
btn_stop Button Stop watching
txt_folderactivity   Textbox Folder activity

Let's start coding this application. The first thing we need to do is to import the required classes. Type the following code before your class declaration.

Imports System.IO
Imports System.Diagnostics

This shall import the necessary class required for our application. We also need to declare a public variable for our FileSystemWatcher class:

Public watchfolder As FileSystemWatcher

Also, add the following code to the btn_start_click procedure.

watchfolder = New System.IO.FileSystemWatcher()

'this is the path we want to monitor
  watchfolder.Path = txt_watchpath.Text

'Add a list of Filter we want to specify
'make sure you use OR for each Filter as we need to
'all of those

watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                           IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                           IO.NotifyFilters.Attributes

' add the handler to each event
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange

' add the rename handler as the signature is different
AddHandler watchfolder.Renamed, AddressOf logrename

'Set this property to true to start watching
watchfolder.EnableRaisingEvents = True

btn_startwatch.Enabled = False 
btn_stop.Enabled = True

'End of code for btn_start_click

The NotifyFilter property is used to specify the type of changes you want to watch. You can combine the notify filters to watch for one or more than one type of changes; for example, you can set the NotifyFilter property to Size if you want to monitor the changes in the file/folder size. Below is the list of notify filters:

Filter Description
Attributes The attributes of the file or folder
CreationTime The time the file or folder was created
DirectoryName   The name of the directory
FileName The name of the file
LastAccess The date the file or folder was last opened
LastWrite The date the file or folder last had anything written to it  
Security The security settings of the file or folder
Size The size of the file or folder

The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName.

The FileSystemWatcher class raises five events: Created, Changed, Deleted, Renamed, and Error. But because the Created, Changed, and Deleted events share the same event signature, we can write just one event handler. We shall write one event handler for Renamed because their event signatures are different.

Let's type code for handling the Created, Changed, and Deleted events raised by the FileSystemWatcher class. (Please note that you will have to type the event declaration; this procedure is not generated automatically.)

Private Sub logchange(ByVal source As Object, ByVal e As _
                      System.IO.FileSystemEventArgs)
  If e.ChangeType = IO.WatcherChangeTypes.Changed Then
      txt_folderactivity.Text &= "File " & e.FullPath & _
                              " has been modified" & vbCrLf
  End If
  If e.ChangeType = IO.WatcherChangeTypes.Created Then
      txt_folderactivity.Text &= "File " & e.FullPath & _
                              " has been created" & vbCrLf
  End If
  If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
      txt_folderactivity.Text &= "File " & e.FullPath & _
                              " has been deleted" & vbCrLf
  End If
End Sub

This is the code for handling the Renamed event raised by the FileSystemWatcher class.

Public Sub logrename(ByVal source As Object, ByVal e As _
                     System.IO.RenamedEventArgs)
   txt_folderactivity.Text &= "File" & e.OldName & _
                 " has been renamed to " & e.Name & vbCrLf
End Sub

And lastly, this is the code for the btn_stop_click, which shall stop the monitor.

' Stop watching the folder
watchfolder.EnableRaisingEvents = False
btn_startwatch.Enabled = True
btn_stop.Enabled = False

Finally

Now it's time to run the application and see it in action. please build and run the application, type the folder you want to monitor in the text box, and click Start Watching to start watching that folder.

In the folder you specified, create a file, rename it, update it, and delete it to see our application recording those changes.

More Information

Use the FileSystemWatcher.Filter property to determine what files should be monitored. For example, setting the filter property to "*.txt" shall monitor all the files with extension txt. The default is *.*, which means all the files with extension are being monitored. If you want to monitor all the files, with and without extensions, please set the Filter property to "".

FileSystemWatcher can be used watch files on a local computer, a network drive, or a remote computer, but it does not raise events for CDs. It only works on Windows 2000 and Windows NT 4.0. Common file system operations might raise more than one event. For example, when a file is edited or moved, more than one event might be raised. Likewise, some anti virus or other monitoring applications can cause additional events.

FileSystemWatcher will not watch the specified folder until the path property has been set and EnableRaisingEvents is set to true.

Set the FileSystemWatcher.IncludeSubdirectories property to true if you want to monitor subdirectories; otherwise, set it to false. The default is false.

The FileSystemWatcher.Path property supports Universal Naming Convention (UNC) paths. If the folder to which the path points is renamed, FileSystemWatcher reattaches itself to the new, renamed folder.

Conclusion

Hopefully, this article has shown you how simple it is to incorporate the FileSystemWatcher class in your application. Here are a few things that you could do with the FileSystemWatcher class:

  • Import a file the moment it is copied/uploaded to a particular folder.
  • Recreate a file if the file is deleted or something else is done to it.
  • Notify all the applications depending upon a file the moment the file is renamed, deleted, or updated.

About the Author

Jayesh Jain works as a consultant in Auckland, New Zealand. He has several years of n-Tier development experience and is currently working with Visual Basic.NET to develop interactive client solutions. He has a passion for Web development and in the spare time he likes to write articles. You can contact him on jainjayesh74@yahoo.com.



Comments

  • The illegal operation error in above code

    Posted by Rj71436 on 10/26/2010 08:01am

    When i used the code above in Visual Studio 2005 it gave error as "Cross thread operation not valid: Control 'txt_folderactivity' accessed from a thread other than the thread it was created on." Can you give me the solution to this problem & if possible the code for solution also.

    • Cross thread operation not valid

      Posted by wdjong on 03/28/2011 08:11pm

      I found that this error occurs in the ide but not if I ran the exe from the bin\debug folder (VS2008)

      Reply
    Reply
  • Remote foloders?

    Posted by Broadbent on 07/03/2006 12:12pm

    Is there a way of watching folders on remote computers?

    Reply
  • user name

    Posted by Legacy on 09/01/2003 12:00am

    Originally posted by: sujit kumar singh

    i would like to know that if a file has been modified of created by a different user via lan how can we get the user name of that person who is operating in the folder

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

  • Live Event Date: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds