Sunday, January 6, 2008

.NET Reference Guide > Monitoring the File System

InformIT: .NET Reference Guide - Monitoring the File System

FileSystemWatcher
Imports System.IO
Module Module1
Const DirectoryName As String = "c:\temp"
Sub Main()
' Create the FileSystemWatcher
Dim myWatcher As New FileSystemWatcher(DirectoryName)
Try
' Add delegates for the desired events
AddHandler myWatcher.Created, New FileSystemEventHandler(AddressOf myWatcher_Created)
AddHandler myWatcher.Changed, New FileSystemEventHandler(AddressOf myWatcher_Changed)
AddHandler myWatcher.Renamed, New RenamedEventHandler(AddressOf myWatcher_Renamed)
AddHandler myWatcher.Deleted, New FileSystemEventHandler(AddressOf myWatcher_Deleted)
' You must set EnableRaisingEvents to true in order for events to be received
myWatcher.EnableRaisingEvents = True
' Display instructions and wait for user to exit program
Console.WriteLine("Make changes to the {0} directory", DirectoryName)
Console.WriteLine("You will see events generated from those changes.")
Console.WriteLine("Press ENTER to exit the program.")
Console.ReadLine()
Finally
myWatcher.Dispose()
End Try
End Sub

' Event handlers respond to events raised by FileSystemEventHandler
Private Sub myWatcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)
Console.WriteLine("File system event: File {0} {1}", _
e.FullPath, e.ChangeType)
End Sub

Private Sub myWatcher_Created(ByVal sender As Object, ByVal e As FileSystemEventArgs)
Console.WriteLine("File system event: File {0} {1}", _
e.FullPath, e.ChangeType)
End Sub

Private Sub myWatcher_Renamed(ByVal sender As Object, ByVal e As RenamedEventArgs)
Console.WriteLine("File system event: File {0} {1} to {2}", _
e.OldFullPath, e.ChangeType, e.FullPath)
End Sub

Private Sub myWatcher_Deleted(ByVal sender As Object, ByVal e As FileSystemEventArgs)
Console.WriteLine("File system event: File {0} {1}", _
e.FullPath, e.ChangeType)
End Sub
End Module