Parham Doustdar
Parham Doustdar

Reputation: 2039

How can I make sure this is the last change in FileSystemWatcher onChanged event?

I am using FileSystemWatcher to read the contents of a file that is written to by another application. The events that happen are as follows:

  1. First, the onCreated event happens.
  2. Then, the onChanged event happens, an unknown number of times (sometimes it's 2, sometimes it's 3, and sometimes it's 4).

Is there a trick to know, in the handler for the onChanged event, that this is the last time this file is being written to by the other application?

Upvotes: 0

Views: 94

Answers (2)

Tim
Tim

Reputation: 2912

I usually handle these by waiting a predefined am out of time and verifying the file hasn't changed since that last check.

IE:

Change event fires

Start timer (use tasks these days)(for some small amount of time ~seconds usually)

If change event fires again, reset timer/task delay

Once the task executes that means the writes have settled down for at least a few seconds, indicating that the file access is done.

*Tweaking the timeout may be needed in some cases depending on file size and accessing programs

Upvotes: 0

Sam Makin
Sam Makin

Reputation: 1556

Any duplicated OnChanged events from the FileSystemWatcher can be detected and discarded by checking the File.GetLastWriteTime timestamp on the file in question. Like so:

Private lastRead As DateTime = DateTime.MinValue

Private Sub OnChanged(source As Object, a As FileSystemEventArgs)
    Dim lastWriteTime As DateTime = File.GetLastWriteTime(uri)
    If lastWriteTime <> lastRead Then
        doStuff()
        lastRead = lastWriteTime
    End If
    ' else discard the (duplicated) OnChanged event
End Sub

Another approach is discussed here

Upvotes: 1

Related Questions