Articles‎ > ‎Technical Articles‎ > ‎

Watching File/Folder Activity in VB.NET

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

Introduction

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

Coding

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 _
                                       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
        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
        MsgBox(Ed.ToString)
    End Sub
    Public Sub _LogRename(ByVal source As Object, ByVal e As _
                            System.IO.RenamedEventArgs)
        Dim Ex As String
        Ex = "File" + e.OldName.ToString + "has been renamed to " + e.Name.ToString
        MsgBox(Ex.ToString)
    End Sub
End Class

Articles