Search code examples
.netvb.netfilesystemwatcherc#-to-vb.net

Create multiple FileSystemWatcher instances dynamically


I have a filesystemwatcher written from examples found here that is working fine, along the lines:

Public monitor As FileSystemWatcher
monitor = New System.IO.FileSystemWatcher()
monitor.Path = c:\temp\
monitor.NotifyFilter = IO.NotifyFilters.DirectoryName
monitor.NotifyFilter = monitor.NotifyFilter Or IO.NotifyFilters.FileName
monitor.NotifyFilter = monitor.NotifyFilter Or IO.NotifyFilters.Attributes

'Add handlers
AddHandler monitor.Changed, AddressOf fileevent
AddHandler monitor.Created, AddressOf fileevent
AddHandler monitor.Deleted, AddressOf fileevent

'Start watching
monitor.EnableRaisingEvents = True

What I'm struggling with is expanding on this to monitor multiple folders, but without knowing except at run time how many folders there will be to monitor.

This question seems to cover it in C# Multiple Configurable FileSystemWatcher methods

But my lack of experience is so far preventing me from managing to translate this to VB.NET


Solution

  • With prompting from Matt Wilko to push my tired brain a bit further I have found a solution, thanks.

    Private fsWatchers As New List(Of FileSystemWatcher)()
    
    Public Sub AddWatcher(wPath As String)
        Dim fsw As New FileSystemWatcher()
        fsw.Path = wPath
        AddHandler fsw.Created, AddressOf logchange
        AddHandler fsw.Changed, AddressOf logchange
        AddHandler fsw.Deleted, AddressOf logchange
        fsWatchers.Add(fsw)
    End Sub
    

    With a handler that looks something like:

    Public Sub logchange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
        'Handle change, delete and new events
        If e.ChangeType = IO.WatcherChangeTypes.Changed Then
            WriteToLog("File " & e.FullPath.ToString & " has been modified")
        End If
    
        If e.ChangeType = IO.WatcherChangeTypes.Created Then
            WriteToLog("File " & e.FullPath.ToString & " has been created")
        End If
    
        If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
            WriteToLog("File " & e.FullPath.ToString & " has been deleted")
        End If
    End Sub
    

    Then call AddWatcher with each of your paths to monitor (from array, XML file or form List depending on your needs) and when you've added all paths set your filters and start monitoring:

    For Each fsw In fsWatchers
            fsw.NotifyFilter = IO.NotifyFilters.DirectoryName
            fsw.NotifyFilter = watchfolder.NotifyFilter Or IO.NotifyFilters.FileName
            fsw.NotifyFilter = watchfolder.NotifyFilter Or IO.NotifyFilters.Attributes
            fsw.EnableRaisingEvents = True
        Next