Search code examples
c#filemove

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


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.


Solution

  • In Windows implemenation of .NET Framework, System.IO.File.Move calls the underlying Win32 function MoveFile.

    MSDN about MoveFile:

    Moves an existing file or a directory, including its children.

    and it seems to be the same function that is called by Windows Explorer. So Yes, it does the same thing, just renaming and not a Copy/Delete.

    public static void Move(String sourceFileName, String destFileName) {
        ...
        ... 
        if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName))
        {
            __Error.WinIOError();
        } 
    }