Click here to Skip to main content
Click here to Skip to main content

Watching Folder Activity in VB.NET

By , 13 Nov 2002
 

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           '      TextBox  (for folder path)
btn_startwatch          '      Button   (start watching)
btn_stop                '      Button   (stop watching)
txt_folderactivity      '      Textbox  (folder activity)
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()

'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, 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       ' (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, 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.
' Stop watching the folder
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jayesh Jain
Business Analyst
New Zealand New Zealand
Member
Working as a Business Analyst for a leading software development organization in New Zealand. I have several years of n-Tier software development experience, about 10+ years in health sector and more than a year in graphics art industry. I am interested in Business improvement process, documentation and knowledge retaining strategies.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralALOT of files really fast crashes the project !membermavamaarten_youtube24 Apr '10 - 6:59 
I'm making an installer.
Now, just to make some 'output log' like seen in alot of installers, I wanted to monitor the output path.
The problem is, it extracts really fast. it's actually so fast it crashes my project (I added doevents...)
 
How can I fix this ?
GeneralFilesystemWatchermembersan0101806 Oct '08 - 6:56 
Hello
  
I Have a problem for monitorear files without extension.
I am using visual studio 2003 and the application install it in windows 2000 server.
The arhivo that comes to the folder is BA1_DaVivienda_COBELST796 without extension
 
this code
 
dim   oWacther = New FileSystemWatcher
            oWacther.Path = "C:\"
            oWacther.Filter = "BA1_DaVivienda_*.*"
            oWacther.IncludeSubdirectories = true
            oWacther.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName)  
            oWacther.EnableRaisingEvents = True
            AddHandler oWacther.Created, AddressOf OnChanged
 
please helpme
 
email is: san010180@hotmail.com
GeneralRe: FilesystemWatchermemberrootjumper19 Oct '09 - 2:42 
oWacther.Filter = "BA1_DaVivienda_*.*"
-> oWacther.Filter = "BA1_DaVivienda_*"
GeneralRe: FilesystemWatcher from Atul patelmemberafr123ert564r817 Aug '11 - 0:23 
replace with following

oWacther.Filter = "BA1_DaVivienda_"
GeneralError: Cross-thread operation not validmemberSiddiq-ur-Rahman Khurram6 Aug '08 - 2:00 
Dear Jain,
 
its pleasure to see this code, because i was tired converting vb6 code to .net for such activity. This is a great job you've done.
 
But when i compiled the code, i got following error.
 
Cross-thread operation not valid: Control 'txt_folderactivity' accessed from a thread other than the thread it was created on.
 
in these lines
 
If e.ChangeType = IO.WatcherChangeTypes.Created Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been created" & vbCrLf
End If

 
Kindly help me.
 
SRK
GeneralRe: Error: Cross-thread operation not validmemberr_mohd6 Aug '08 - 22:30 
hi
i am also facing the same problem,pl help.
 
rmshah
Developer

GeneralRe: Error: Cross-thread operationmemberafr123ert564r817 Aug '11 - 0:25 
reply from Atul Patel
 
add this line at sub or function starting .
 
Control.CheckForIllegalCrossThreadCalls = False
GeneralMicrosoft examplememberkelvin19972 Aug '08 - 4:42 
Guys I think you should also take a look at this link. It has more details.
 
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(VS.71).aspx[^]
QuestionCopy Directorymembermuhamad imran30 Jun '08 - 1:24 
Hi Derar All
i m new in dot net and working in vb.net
i want to copy the directories and subdirectories from a location and past them to an other location
so pleas help me how can i do
thanks in Advance
AnswerRe: Copy Directorymemberr_mohd6 Aug '08 - 22:26 
hi
Try this
My.Computer.FileSystem.CopyDirectory("C:\SourceDirectory", "D:\DestinationDirectory")
NoteFrown | :-( system.io) name space is required.
 
rmshah
Developer

AnswerRe: Copy Directorymemberchaos015327 Jul '12 - 22:19 
try this. i am currently building a file watcher program that checks a folder activity and then copy/cut it into another folder set by the user. 'this code below came from the insert snippet feature
 
'this code below came from the insert snippet feature
My.Computer.FileSystem.CopyFile("C:\Source.txt", "C:\NewFolder\Dest.txt") 
 
'but this is the one i use
 System.IO.File.Copy("C:\Source.txt", "C:\NewFolder\Dest.txt")
 
i hope this helps
General"created" event fires.. followed by delete, another create, and two rename eventsmembervegeta4ss20 Mar '08 - 4:52 
I'm not sure why this is occuring but when I create a new file into the monitored folder it should only log once that a new file was created. However, it actually does a created log, a deleted, another created, and then two file rename events.
 
I've read through the comments and made the changes suggested by others but am still receiving this issue.
 
Anyone else have the issue? Any workaround?
GeneralRe: "created" event fires.. followed by delete, another create, and two rename eventsmembervegeta4ss20 Mar '08 - 7:07 
turns out notepad and wordpad only have this effect. They handle it differently according to a couple articles I found.
 
A batch that creates 20 files in the watched folder only registers 20 changed events which is what I need.
Questionhow about monitoring network storage?membermpmalajos19 Sep '07 - 21:33 
i have a problem regarding monitoring an NAS storage system. it triggers no event or what so ever..
QuestionDoes FilesystemWatcher use DDE anyhow???membersonumutneja13 Sep '07 - 19:53 
i got a problem in one application that it block out some other applications if FileSystemWatcher is used. So i wanted to know does FilesystemWatcher use DDE anyhow?????
 
Thanks in advance.
 
Reply soon.WTF | :WTF:
Generaldirectories and sub direectoriesmemberGC9N6 Jun '07 - 22:38 
is there any way to create subdirectories too?
GeneralFile creatormemberletmetanka16 May '07 - 1:20 
Is it possible to see who creates a file, or at least get the creting computers name or something, if a folder on a network beeing watched.
Here is a more detailed explanation of what im after.
http://www.xtremevbtalk.com/showthread.php?t=283409[^]
 
/Bagera
QuestionCross Thread issuesmemberHD-P27 Apr '07 - 8:56 
When I tried your code in VS 2005 I get cross thread issues when any of the IO.WatcherChangeTypes or IO.RenamedEventArgs try to fire. I found a solution using
 
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
Code that had issues
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = True
 
I am a Real Green programmer-wanna-beUnsure | :~ and would appreciate any help.
 

 
Thanks...
AnswerRe: Cross Thread issuesmemberSchadenfroh28 May '07 - 6:02 
Try using a variable intermediate before writing it to an object on the form instead of disabling the check for illegal calls.
GeneralRe: Cross Thread issuesmemberibless12 Nov '07 - 8:48 
this is a solution for your thraed but in vb.net 2005
first add this
------------------------------
Imports System.IO
Imports System.Diagnostics
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.Windows.Forms
------------------------------
second add this private sub
-------------------
Private Sub SetText(ByVal [text] As String)
If Me.txt_folderactivity.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.txt_folderactivity.Text &= [text] & vbCrLf
End If
End Sub
----------------------------
in any formula like this :
' txt_folderactivity.Text &= "File " & e.FullPath & " has been created" & vbCrLf
change it to this or retype it in this code :
Dim b As String
b = "File " & e.FullPath & " has been created" ' & vbCrLf
SetText(b)
------------------------------
i hope it will be okay
Roll eyes | :rolleyes:
GeneralRe: Cross Thread issuesmemberibless12 Nov '07 - 8:52 
add this sorry i forget it after Public Class Form1
----------------------------------------------
Public watchfolder As FileSystemWatcher
Delegate Sub SetTextCallback(ByVal [text] As String)
----------------------------------------------
GeneralRe: Cross Thread issuesmemberrgkamble12 Aug '08 - 21:14 
Add the following code to project
to get rid of error:'cross thread exception'
i got this resolution when i discuss this issue with my colleague
munaf khatri
declare variable : Public str As String = ""
1) add method
Private Sub AssignData()
Me.txt_folderactivity.Text = str
End Sub
2) modify existing method logchange:
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
 

If e.ChangeType = IO.WatcherChangeTypes.Changed Then
If Me.txt_folderactivity.InvokeRequired Then
str = "File " & e.FullPath & " has been modified" & vbCrLf
txt_folderactivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderactivity.Text = str
End If
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
If Me.txt_folderactivity.InvokeRequired Then
str = "File " & e.FullPath & " has been created" & vbCrLf
txt_folderactivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderactivity.Text = str
End If
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
If Me.txt_folderactivity.InvokeRequired Then
str = "File " & e.FullPath & " has been deleted" & vbCrLf
txt_folderactivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderactivity.Text = str
End If
End If
End Sub
 

 
3) simillarly you can write a code for Rename method.
 
Rahul G. Kamble

AnswerRe: Cross Thread issuesmemberemmaddais21 Jun '09 - 5:03 
Hi, thanks to you all guy i've been able to correct toe original code posted by Jayesh Jain
I implemented the additional codes posted by rgkamble and this was how i did it.
 
Imports System.IO
Imports System.Diagnostics
 
Public Class Form1
Public watchfolder As FileSystemWatcher
Public str As String = ""
 
Private Sub btn_startwatch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_startwatch.Click
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 = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName Or NotifyFilters.Attributes)
 
' Only watch text files.
watchfolder.Filter = "*.txt"
 
' 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
 
Me.btn_startwatch.Enabled = False
Me.btn_stopwatch.Enabled = True
'End of code for btn_start_click
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
If Me.txt_folderActivity.InvokeRequired Then
str = "File " & e.FullPath & " has been modified" & vbCrLf
txt_folderActivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderActivity.Text = str
End If
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
If Me.txt_folderActivity.InvokeRequired Then
str = "File " & e.FullPath & " has been created" & vbCrLf
txt_folderActivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderActivity.Text = str
End If
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
If Me.txt_folderActivity.InvokeRequired Then
str = "File " & e.FullPath & " has been deleted" & vbCrLf
txt_folderActivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderActivity.Text = str
End If
End If
End Sub
 
Public Sub logrename(ByVal source As Object, ByVal e As _
System.IO.RenamedEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Renamed Then
If Me.txt_folderActivity.InvokeRequired Then
str = "File" & e.OldName & " has been renamed to " & e.Name & vbCrLf
txt_folderActivity.Invoke(New MethodInvoker(AddressOf AssignData))
Else
txt_folderActivity.Text = str
End If
End If
End Sub
 
Private Sub btn_stopwatch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_stopwatch.Click
' Stop watching the folder
watchfolder.EnableRaisingEvents = False
btn_startwatch.Enabled = True
btn_stopwatch.Enabled = False
End Sub
 
Private Sub AssignData()
Me.txt_folderActivity.Text = str
End Sub
End Class

 
and it works well for me.
Maybe the only thing someone has to help me with is that, even if i rename a txt file, it on tells me that the file is modified, instead of renamed.
Thanks.
 
emmaddais

QuestionHow to set filter for a specific set of files?membergarimajain_mca21 Dec '06 - 19:14 
Is it Possible to watch a folder for the files that has “member” as a substring in the file name?
QuestionIs it possible to monitor more than one folder?memberjerryoz18 Jul '06 - 3:59 
If so, can you please post a sample code.
 
Thanks,
 
Yaron

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 14 Nov 2002
Article Copyright 2002 by Jayesh Jain
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid