Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# File.Move vs Rename - Does it actually Move the file or just rename it?

Tags:

c#

file

move

After reading this stackoverflow post on how to "Rename" a file the solution turns out to be using the Files.Move or Directory.Move methods.

I know in Windows if I do a rename it is instantaneous, as I assume it is not so much moving the file on the drive as it is changing the location on some indexing somewhere.

When I use Files.Move or Directory.Move is it going to do the same thing, or is it going to do a Copy and then a Delete?

I am trying to avoid the wear and tear on my drives.

like image 759
Kairan Avatar asked May 03 '15 17:05

Kairan


2 Answers

Please refer to the documentation of the underlying Win32 API used by File.Move:

The MoveFile function will move (rename) either a file or a directory (including its children) either in the same directory or across directories. The one caveat is that the MoveFile function will fail on directory moves when the destination is on a different volume. If a file is moved across volumes, MoveFile does not move the security descriptor with the file. The file will be assigned the default security descriptor in the destination directory. The MoveFile function coordinates its operation with the link tracking service, so link sources can be tracked as they are moved.

Regarding your question:

Is it going to do a Copy and then a Delete?

The only time when it will do a "Copy" and then a "Delete" is if you move the file across separate disks.

like image 74
Alex Avatar answered Nov 15 '22 01:11

Alex


When I use Files.Move or Directory.Move is it going to do the same thing

Technically, it's not going to do anything to the file. It's going to make a system call to the underlying OS to perform the move operation.

So in that sense, yes, it will do the same thing. When you instruct Windows Explorer to "move" a file it, much as you summarize, effectively just re-indexes something somewhere. (That part is handled by the file system, which the OS uses.) When you perform these functions in .NET code, at some level deeper in the framework they're essentially invoking the same OS-level operations that Windows Explorer does.

or is it going to do a Copy and then a Delete

I don't think I've ever seen a file system which performs a move operation in this way. (Short of one written by some novice or student as an academic project perhaps.) If one does exist, it's highly unlikely that it would be in common use by any operating system you're likely to encounter.

Basically the software (whether it's Windows Explorer or code in the .NET Framework) tells the OS to perform the operation. The OS tells the file system to perform the operation. The file system itself should be very optimized to do this.

like image 28
David Avatar answered Nov 15 '22 01:11

David