Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming Directory with same name different case

I am trying to rename a directory in c# to a name that is the same only with differing case.

For example: f:\test to f:\TEST

I have tried this code:

var directory = new DirectoryInfo("f:\\test");
directory.MoveTo("f:\\TEST");

and I get a IOException - Source and destination path must be different. I have also tried Directory.Move() with the same result.

How is this done? Do I have to create a separate temp directory, move the contained files from the original directory to the temp directory, and then delete the original, and rename the temp directory?

like image 473
scott Avatar asked Oct 26 '09 00:10

scott


3 Answers

Even if the .NET method DirectoryInfo.MoveTo throws an exception if the name is the same, you can call the Windows API MoveFile function like this to set the casing of the directory name:

bool success = MoveFile(dirInfo.FullName, dirInfo.FullName);

With this extern declaration:

[DllImport("kernel32", SetLastError = true)]
private static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);

It works fine for me when the name differs in case only. I haven't tried calling it like this when the name is already exactly as specified.

This has the advantage that the directory never disappears under its original name.

It has the disadvantage though that it only works on Windows.

like image 124
ygoe Avatar answered Oct 18 '22 13:10

ygoe


Well, you don't need to create a separate directory and move everything. Just rename the folder to something different and then back to the name you want:

var dir = new DirectoryInfo(@"F:\test");
dir.MoveTo(@"F:\test2");
dir.MoveTo(@"F:\TEST");
like image 44
Joey Avatar answered Oct 18 '22 14:10

Joey


Why not rename the directory temp and then rename again to TEST ?

like image 31
pavium Avatar answered Oct 18 '22 15:10

pavium