C# - How to rename a directory

In all cases, if the destination directory already exists, the operation will fail.

Using C# only:

string oldpath;
string newpath;
// Using System.Directory
Directory.Move(oldpath, newpath);
// Using System.IO.DirectoryInfo
new DirectoryInfo(oldpath).MoveTo(newpath);

Using C# with P/Invoke:

// Using Win32 MoveFile
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);
bool ret = MoveFile(oldpath, newpath);
int error = Marshal.GetLastWin32Error();
// Using Win32 MoveFileEx
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint flags);
bool ret = MoveFileEx(oldpath, newpath, 0);
int error = Marshal.GetLastWin32Error();

Ads by Google

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

© Richard McGrath