I have not found an ideal solution to this issue. Windows fires the event
multiple times as the file is being created. Check out the FileMon tool on
SysInternals.com to watch some of the IO that is happening behind the scenes.
The FileSystemWatcher is essentially a wrapper around the WIN32 API's that
handle the IO messages.
In my case, I have used the following scheme to handle the case of a file
that is being uploaded to wait until the upload has completed before processing.
Public Sub ProcessFile()
Sleep(1000) 'Wait a bit before proceeding to let them finish
TRY
'Move the file to a processing directory
Catch ex as System.IO.IOException
'File not yet availabl, wait and try again
ProcessFile()
Exit Sub
End Try
'Proceed with processing the file in the new temp location.
If the file writing took a further minute from the point at which you
first call ProcessFile, would you not end up with 60 calls to
ProcessFile with 60 exceptions sitting on the stack?
Wouldn't the following be better:
Public Sub ProcessFile()
Dim bAvailable as Boolean = False
While Not bAvailable
Try
'Move the file to new location
bAvailable = True
Catch Ex as System.IO.IOException
'Optionally, count how many times we reach here
'and if it's a large number, call Throw, since it doesn't
'seem like we'll ever succeed
Sleep(1000)
End Try
End While
'Proceed with processing
End Sub
I'm trying to work out if there's a way to tell whether we can access
the file which doesn't invoke exception handling. Not sure.
Damien