none
MoveFile API function fails with error code 5 Access Denied

    Question

  • I have a trivial 32-bit Delphi application that renames a file via the MoveFile function.

    program MoveFileTest;
    {$APPTYPE CONSOLE}
    {$R *.res}
    uses
      System.SysUtils,
      WinAPI.Windows;
    begin
      try
        if not MoveFile(PWideChar(ParamStr(1)), PWideChar(ParamStr(2))) then
          RaiseLastOSError;
      except
        on E: Exception do
          Writeln(E.ClassName, ': ', E.Message);
      end;
    end.

    What puzzles me is that the MoveFile call fails with the operating system error 5 - Access denied. There is something on my system that prevents renaming a file in this way.

    The file I try to rename is created by me, not read-only and I have all the necessary rights. I can rename it via Windows Explorer and via the move command, but when I use this program it fails.

    C:\Temp>move test1.txt test2.txt
            1 file(s) moved.
    
    C:\Temp>MoveFileTest.exe test2.txt test1.txt
    EOSError: System Error.  Code: 5.
    Access is denied
    
    C:\Temp>

    You could say that the program is incorrectly written, but running the same program under the Administrator account perfectly works. The same program on another machine (Windows 8 x64) works.

    C:\Temp>MoveFileTest.exe test2.txt test1.txt
    
    C:\Temp>dir test1.txt
     Volume in drive C is System
     Volume Serial Number is 444D-5B8C
    
     Directory of C:\Temp
    
    03.07.2013  16:50                 4 test1.txt
                   1 File(s)              4 bytes
                   0 Dir(s)  402 360 365 056 bytes free
    I am completely confused, how can this happen?

    My test machine (where the program fails) is Windows 7 x64. I work under a limited user account on both machines. UAC is enabled on both machines.








    Wednesday, July 03, 2013 11:38 AM

Answers