Win32 - MoveFileEx with REPLACE_EXISTING returns Access Denied error 5

The problem

If you try to use the MoveFileEx function to rename a directory, and the target directory already exists, the function will fail with error number 5 (Access Denied), even if you pass MOVEFILE_REPLACE_EXISTING.

Why?

MOVEFILE_REPLACE_EXISTING works for files only, not directories.

The MSDN documentation for MoveFileEx states:
MOVEFILE_REPLACE_EXISTING This value cannot be used if lpNewFileName or lpExistingFileName names a directory.

Example code

The following C# code illustrates the problem:

We are attempting to rename the directory 'c:\temp\old-dir' to 'c:\temp\new-dir' using MoveFileEx with the MOVEFILE_REPLACING_EXISTING (0x1) flag.

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint flags);
 
var oldDir = @"c:\temp\old-dir";
var newDir = @"c:\temp\new-dir";
 
Directory.CreateDirectory(oldDir);
Directory.CreateDirectory(newDir);
 
const uint MOVEFILE_REPLACE_EXISTING = 0x1;
bool ret = MoveFileEx(oldDir, newDir, MOVEFILE_REPLACE_EXISTING);
int error = Marshal.GetLastWin32Error();
// ret = false
// error = 5. Access is denied.

Summary

MOVEFILE_REPLACING_EXISTING is for file operations only.


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath