Detect when a file or folder changes with VB.NET

This is the .NET equivalent of my VB6 Folder Spy program. In .NET this is much easier thanks to the FileSystemWatcher class from the System.IO namespace.

    Imports System.IO

    '
    ' Create a FileSystemWatcher object passing it the folder to watch.
    '
    Dim fsw As New FileSystemWatcher("C:\temp")
    '
    ' Assign event procedures to the events to watch.
    '
    AddHandler fsw.Created, AddressOf OnChanged
    AddHandler fsw.Changed, AddressOf OnChanged
    AddHandler fsw.Deleted, AddressOf OnChanged
    AddHandler fsw.Renamed, AddressOf OnRenamed

    With fsw
        .EnableRaisingEvents = True
        .IncludeSubdirectories = True
        '
        ' Specif the event to watch for.
        '
        .WaitForChanged(WatcherChangeTypes.Created Or _
                        WatcherChangeTypes.Changed Or _
                        WatcherChangeTypes.Deleted Or _
                        WatcherChangeTypes.Renamed)
        '
        ' Watch certain file types.
        '
        .Filter = "*.txt"
        '
        ' Specify file change notifications.
        '
        .NotifyFilter = (NotifyFilters.LastAccess Or _
                         NotifyFilters.LastWrite Or _
                         NotifyFilters.FileName Or _
                         NotifyFilters.DirectoryName)
    End With


    Public Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
        Debug.Fail("File changed: " & e.FullPath & " change type: " & e.ChangeType)
    End Sub

    Public Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
        Debug.Fail("File renamed from: " & e.OldName & " to: " & e.Name)
    End Sub


About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page