Search code examples
vb.netfilesystemwatcher

FileSystemWatcher is not firing events


As a newbie in vb I have some troubles in my FileSystemWatcher. For some ominous reason it does not fire any events. I want to check for files being copied, deleted or edited in the directory.

I appreciate any help!!

Here is my code:

Public Class FileWatcher

Public Sub run(path As String)
    Dim watcher As New FileSystemWatcher()

    watcher.Path = path
    watcher.Filter = "*.xml"
    watcher.NotifyFilter = NotifyFilters.FileName Or NotifyFilters.LastWrite Or NotifyFilters.CreationTime

    AddHandler watcher.Changed, AddressOf OnChanged
    AddHandler watcher.Created, AddressOf OnChanged
    AddHandler watcher.Deleted, AddressOf OnChanged
    AddHandler watcher.Renamed, AddressOf OnRenamed

    watcher.EnableRaisingEvents = True

End Sub


Public Function OnChanged(source As Object, e As FileSystemEventArgs) As String
    ' Returns file name for later use
    Console.WriteLine("Monitoring: " + e.FullPath)
    Return e.FullPath
End Function

Public Function OnRenamed(source As Object, e As RenamedEventArgs) As String
    Console.WriteLine("Monitoring: " + e.FullPath)
    Return e.FullPath
End Function

End Class


Solution

  • The first thing to consider here is the fact that the watcher is a local variable inside the run method. This means that your watcher will be garbage collected immediately after exiting from the run method. You need to declare it at the globlal class level and keep an instance of that class live until you have finished to use the monitoring code.

    Public Class FileWatcher
         Dim watcher As New FileSystemWatcher()
    
         Public Sub run(path As String)
    
            ....
    

    Next keep in mind that OnChanged and OnRenamed are event handlers thus they should be declared as Sub not as Function. And of course they don't return anything

    If you need the value from those handlers you need to implement some kind of global variables that keeps your data for further processing. An example could be a list (The list of strings should be expanded to differentiate between added and deleted files or better use your own class and a list of this classes instances)

    Dim changedFiles = new List(Of String)()
    Dim renamedFiles = new List(Of String)()
    Public Sub OnChanged(source As Object, e As FileSystemEventArgs) 
        Console.WriteLine("Monitoring: " + e.FullPath)
        changedFiles.Add(e.FullPath)
    End Sub
    
    Public Sub OnRenamed(source As Object, e As RenamedEventArgs)
        Console.WriteLine("Monitoring: " + e.FullPath)
        renamedFiles.Add(e.FullPath)
    End Sub