Search code examples
c#imagerenamefile-move

Most efficient way to rename an image


Is there a more efficient way to rename a file in Windows other than:

System.IO.File.Move(sourceFileName, destFileName);  

I have millions of them and using the above will take almost a week to run.


Solution

  • File.Move is a thin wrapper around the Win32 API. I doubt there is any faster way short of directly modifying the raw data at the block level on the disk. I think you are out of luck looking for a faster way from managed code.

    File.Move decompiled source:

    public static void Move(string sourceFileName, string destFileName)
    {
        if ((sourceFileName == null) || (destFileName == null))
        {
            throw new ArgumentNullException((sourceFileName == null) ? "sourceFileName" : "destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
        }
        if ((sourceFileName.Length == 0) || (destFileName.Length == 0))
        {
            throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), (sourceFileName.Length == 0) ? "sourceFileName" : "destFileName");
        }
        string fullPathInternal = Path.GetFullPathInternal(sourceFileName);
        new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new string[] { fullPathInternal }, false, false).Demand();
        string dst = Path.GetFullPathInternal(destFileName);
        new FileIOPermission(FileIOPermissionAccess.Write, new string[] { dst }, false, false).Demand();
        if (!InternalExists(fullPathInternal))
        {
            __Error.WinIOError(2, fullPathInternal);
        }
        if (!Win32Native.MoveFile(fullPathInternal, dst))
        {
            __Error.WinIOError();
        }
    }