I've seen multiple version of this question on this site, but none seems to address my precie problem, so here it is:
I'm trying to copy a file, using System.Copy
. The destination, if it exists, should be overwritten. I had been using a single line of code for about a month, without problems :
IO.File.Copy(SourceFile, DestFile, True)
But problems started about a week ago, when I started more advanced checks. Partially locked files fail to copy, and the destination gets deleted. Locked files, on the other hand, work correctly: they just trigger a file in use exception.
So I added this line before launching the copy:
Using TestForAccess As New IO.FileStream(SourceFile, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None) : End Using
This was supposed to launch an error if the file was in use. But it is to sensitive. Some files (such as thunderbird's abook.mab) trigger an error in this added code, whereas they copied fine before (and you can copy them in explorer).
My question basically is: How do I tell the system: copy source
to destination
if possible; if not, don't break destination
?
Thanks for your help, this thing is driving me nuts.
Use a two step process--copy to a temp file, then rename to destination. That way if the copy fails, the destination file won't be overwritten.
Even better, you four steps. copy to temp, rename dest to other temp, rename temp to dest, delete other temp.
My VB is rusty, but something like this:
Dim DestTemp As String = DestFile + ".temp"
Dim DestBack As String = DestFile + ".bak"
File.Copy(SourceFile, DestTemp, True)
File.Move(DestFile, DestBack)
File.Move(DestTemp, DestFile)
File.Delete(DestBack)