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:
onCreated
event happens.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?
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