Watching File/Folder Activity in VB.NET

posted Sep 17, 2009, 10:17 AM by Thiyagaraaj M   [ updated Sep 17, 2009, 10:19 AM ]


The FileSystemWatcher class raises five events, which are Created, Changed, Deleted, Renamed and Error. Because Created, Changed, and Deleted events share the same event signature, we can write just one event handler. 

Getting Started

Create New Project In Visual Stuido 2005(Choose VB)

Create Controls and Its Name

Form - Backup
TextBox - txt_Spath
Button - btn_Browse
Folder Browser Dialog - dlg_Fb


Imports System.IO
Imports System.Diagnostics
Public Class Backup
    Public watchfolder As FileSystemWatcher
    Private Sub btn_Browse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Browse.Click
        If dlg_Fb.ShowDialog = Windows.Forms.DialogResult.OK Then
            txt_Spath.Text = dlg_Fb.SelectedPath.ToString
            watchfolder = New System.IO.FileSystemWatcher()
            watchfolder.Path = txt_Spath.Text
            watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
            watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
            watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
            AddHandler watchfolder.Changed, AddressOf _LogChange
            AddHandler watchfolder.Created, AddressOf _LogChange
            AddHandler watchfolder.Deleted, AddressOf _LogChange
            AddHandler watchfolder.Renamed, AddressOf _LogRename
            watchfolder.EnableRaisingEvents = True
        End If
    End Sub
    Private Sub _LogChange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
        Dim Ed As String
        If e.ChangeType = IO.WatcherChangeTypes.Changed Then
            Ed = "File " + e.FullPath.ToString + " has been created".ToString
        End If
        If e.ChangeType = IO.WatcherChangeTypes.Created Then
            Ed = "File " + e.FullPath.ToString + " has been created".ToString
        End If
        If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
            Ed = "File " + e.FullPath.ToString + " has been deleted".ToString
        End If
    End Sub
    Public Sub _LogRename(ByVal source As Object, ByVal e As _
        Dim Ex As String
        Ex = "File" + e.OldName.ToString + "has been renamed to " + e.Name.ToString
    End Sub
End Class
??  Wiziontech Solutions | Created by Thiyagaraaj