Checking that a file is not in the process of being copied

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can I check that a file is not in the process of being copied ?

I want to copy a file from a source path to a destination path, but if the
file is in the process of being copied to the source path, then my code will
fail. If it is in the process of being copied then my code needs to wait for
the copying to finish.

The code below is what I tried, but file.length returns the full file
length, even when the whole file hasn't finished copying.

Any ideas ?
Craig



Private Shared Sub CheckFileCopyComplete(ByVal filePath As String)

Const MAX_TIME_IN_SEC As Integer = 60 * 5 '5 mins
Const PAUSE_IN_MILLISEC As Integer = 500 '0.5 sec

Dim file As New IO.FileInfo(filePath)
Dim fileLength As Long = 0
Dim startTime As DateTime = System.DateTime.Now

Do Until file.Length = fileLength
fileLength = file.Length
System.Threading.Thread.Sleep(PAUSE_IN_MILLISEC)
If System.DateTime.Now.Subtract(startTime).Seconds > MAX_TIME_IN_SEC
Then
Throw New ApplicationException("Timeout waiting for file to copy")
End If
Loop

'file finished copying: move on

End Sub
 
Thanks, but I do not want to be alerted when a file has been created, but
just check that a file is not in the process of being copied before I perform
some operation on it.
 
I decided to catch the exception, pause and then try again (as suggested),
but it meant searching through the ex.message for "because it is being used
by another process".

I have copied the procedure below. If anyone have a neater way to do this,
please let me know.

Thanks,
Craig


Private Sub CopyFileWhenReady(ByVal source As String, ByVal dest As String)

Const MAX_TIME_IN_SEC As Integer = 60 * 5 '5 mins
Const PAUSE_IN_MILLISEC As Integer = 500 '0.5 sec
Const ERROR_MSG_EXRACT As String = "because it is being used by another
process"

Dim copiedOk As Boolean = False
Dim startTime As DateTime = System.DateTime.Now

Do Until copiedOk
Try
IO.File.Copy(source, dest)
copiedOk = True
Catch ex As IO.IOException
If ex.Message.IndexOf(ERROR_MSG_EXRACT) > -1 Then
System.Threading.Thread.Sleep(PAUSE_IN_MILLISEC)
If System.DateTime.Now.Subtract(startTime).Seconds > MAX_TIME_IN_SEC
Then
Throw New ApplicationException("Timeout waiting for file to copy")
End If
Else
Throw ex
End If
End Try
Loop

End Sub
 
Try to see the documentation for the exact exception you should catch. In
most cases you'll find additional members (I believe this is ErrorCode or
HResult or something similar) that gives some additional information about
the problem...

The text could perhaps change and is likely localized either depending on
the os or the language pack...

You could also try perhaps to open the file in exclusive mode before doing
the copy...
 
Back
Top