From the documentation of File.Move
:
Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. You cannot use the Move method to overwrite an existing file.
In short, you can't overwrite on Move
, so in order to facilitate overwriting on Move I mimic the behavior by doing a File.Copy
followed by a File.Delete
. Something like:
if (File.Exists(dstFileName))
{
// System.IO.File.Move cannot be used to overwrite existing files, so we're going
// to simulate that behavior with a Copy & Delete.
File.Copy(procContext.FileName, dstFileName);
File.Delete(procContext.FileName);
}
else
File.Move(procContext.FileName, dstFileName);
My question is: Are there any situations that I need to guard against which could lead to the source file being deleted without it first being successfully copied?
My understanding from reading the documentation is that since File.Copy
doesn't return anything that it should throw an exception in any case that it doesn't succeed. Has anyone encountered any situations where this isn't true?
Move(String, String, Boolean) Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.
Moving – move the original files or folder from one place to another (change the destination). The move deletes the original file or folder, while copy creates a duplicate.
'Frequently asked question: Is MoveFileEx atomic if the existing and new files are both on the same drive? The simple answer is "usually, but in some cases it will silently fall-back to a non-atomic method, so don't count on it". '
I suggest you to probe first if the target file exists and if yes, delete it. Then execute a normal move operation.
Since this sequence is not atomic, in case the destination exists you might want to rename it instead of deleting it, to avoid losing it in case the move fails.
The correct way to do it would be to call
File.Replace(source, destination, copy)
That does the trick for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With