Directory.Move Is Case Insensitive

In order to rename file one would use code that looks something like this:

File.Move("file1.txt", "file2.txt");
File.Move("file.txt", "FILE.txt");

Both lines work without any issue, just as you would expect it.

What happens when we do rename with directories (aka folders):

Directory.Move("dir1", "dir2");
Directory.Move("dir", "DIR");

First line works but second one raises IOException (Source and destination path must be different). For some reason Directory.Move does case insensitive checks. For this to work we need slightly different code:

Directory.Move("dir", "DIR.somereallyunexpectedtext");
Directory.Move("DIR.somereallyunexpectedtext", "DIR");

This code first renames directory to temporary name and then renames it to desired one. Tricky code not shown here is exception handling. Either Directory.Move can fail and thus we would need code like this:

Directory.Move("dir", "DIR.somereallyunexpectedtext");
try {
Directory.Move("DIR.somereallyunexpectedtext", "DIR");
} catch (IOException) {
Directory.Move("DIR.somereallyunexpectedtext", "dir");
} catch (UnauthorizedAccessException) {
Directory.Move("DIR.somereallyunexpectedtext", "dir");
}

For any failure cause we need to do rollback (renaming it back to original name from intermediate one). And worst thing is that, if second rename fails, there is probably no chance in rollback working anyhow. Most common solution? Just forget about handling exceptions and rollback between those two renames. Probability is on your side that, if first operation passes, other will pass too.

Leave a Reply

Your email address will not be published. Required fields are marked *