Search code examples
vb.neteventsfilesystemwatcherraiseevent

How Can I RaiseEvent Manually For A FileSystemWatcher


I have extended on the FileSystemWatcher class to incorporate a FolderCount monitor and FolderEmpty monitor that raise events if a folder reaches a specified amount of files or if a folder returns to an empty status. I seem to have this working and I'm getting events raised when these conditions occur.

However, my problem is that when my FileSystemWatcher first initializes, it automatically goes in to check the folder contents of the specified folder to get a file count. If the limit is already reached, I need to raise an event immediately rather than wait for the FileSystemWatcher to report it.

Currently I can only seem to raise events by plugging into the .Created and .Deleted calls, however, because no files are getting created or deleted, I don't know how to raise my event manually.

Public Sub Initialize()
        SetFolderCountStatus() 'Set the isFolderEmpty flag based on file contents
        If Not isFolderEmpty Then
            If options.WatchForFolderCount Then 
                If FileCountReached(options.FileCountToWatch) Then
                    RaiseEvent EventFolderCount(sender, e) 'Sender and e are never defined
                End If
            End If
        End If
    End Sub

My problem is that both sender and e are never populated with anything because they sit outside of my WatcherEventArgs.

I'm sure this can be done a better way, but I am unsure. Any help would be appreciated. Thanks


Solution

  • I actually resolved this by changing my EventHandler to only require a String variable, rather than EventArgs:

    Public Event EventFolderCount(filename As String)
    

    This way I could call it easily inside and outside of the FileSystemWatcher like so:

    RaiseEvent EventFolderCount(filename)
    

    Thanks @Dave Anderson for pointing me in the right direction.