Search code examples
c#.netvb.netfilesystemwatcher

filesystemwatcher check last detection


I'm using FileSystemWatcher to monitor my folder in .net and I'm firing Created, Changed and Renamed events.

In Created and Renamed events, NotifyFilteris NotifyFilters.FileName In Changed event it is set to NotifyFilters.LastWrite

Now.. I want to not fire these events if the last firing was past than 1 second. So every firing have to be delayed of 1 second. This means also that it can skip the files changed/renamed/created between this delay. Just not to do anything while is delayed.

I searched and tried a lot but I couldn't sort it out.


Solution

  • Create a timestamp that represents the next valid time to process the event. Then, in the event handlers, check the current time against that time.

    Public Class MyClass
        Dim NextValidTime as DateTime
    
        public sub Some_Event_Handler()
            If Now() > NextValidtime Then
                'do stuff
                NextValidTime = DateAdd(DateInterval.Second, 1, Now)
            Else
                ' Not enough time has passed - do nothing
            End If
        end sub
    End Class