Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mimic File.Move if the destination already exists [duplicate]

Tags:

c#

file

copy

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?

like image 985
M.Babcock Avatar asked Apr 24 '12 20:04

M.Babcock


People also ask

Does file move overwrite?

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.

Does file move delete?

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.

Is file move an atomic?

'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". '


2 Answers

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.

like image 195
Tudor Avatar answered Nov 15 '22 22:11

Tudor


The correct way to do it would be to call

File.Replace(source, destination, copy)

That does the trick for me

like image 20
Arsen Zahray Avatar answered Nov 15 '22 22:11

Arsen Zahray