Introduction
Ever wanted to write an application which constantly monitors a folder and
raises events when there is any activity in that folder? In the good old days using VB6 or older you had to use
the windows APIs to do something like this which was not very simple and required lots of coding.
The Microsoft .NET Framework has introduced classes like System.IO
and
System.Diagnostics
, which contains the FileSystemWatcher
class which can raises 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:
txt_watchpath
btn_startwatch
btn_stop
txt_folderactivity
Lets start coding for this application, 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()
watchfolder.Path = txt_watchpath.Text
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
AddHandler watchfolder.Renamed, AddressOf logrename
watchfolder.EnableRaisingEvents = True
btn_startwatch.Enabled = False
btn_stop.Enabled = True
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, eg. set the
NotifyFilter
property to Size if you want to monitor the changes in the file/folder size. Below are the list of notify filters
Attributes
CreationTime
DirectoryName
FileName
LastAccess
LastWrite
Security
Size
The default is the bitwise OR combination of
LastWrite
,
FileName
, and
DirectoryName
.
The FileSystemWatcher
class raises five events, which are Created, Changed, Deleted, Renamed and Error, but because Created, Changed, and Deleted events share the same event signature we can write just one event handler and 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 you will have to type the event declaration, as 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.
watchfolder.EnableRaisingEvents = False
btn_startwatch.Enabled = True
btn_stop.Enabled = False
Finally
Now it's the 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 FileSystemWatcher.Filter
Property to determine what files should be monitored, eg setting filter property to "*.txt" shall monitor all the files with extension txt, the default is *.* which means all the files with extension, if you want to monitor all the files with and without extension 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 CD. 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.
The 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, false. The default is false.
FileSystemWatcher.Path
property supports Universal Naming Convention (UNC) paths.
If the folder, which the path points is renamed the 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 few things that you could do with FileSystemWatcher class
- Import a file the moment it is copied/uploaded to a particular folder
- Recreate a file if the file is deleted or do something else.
- Notify all the applications depending upon a file the moment the file is renamed, deleted or updated.