string FileSystemCasing = new System.IO.DirectoryInfo("H:...").FullName;
EDIT:
As iceman pointed out, the FullName returns the correct casing only if the DirectoryInfo (or in general the FileSystemInfo) comes from a call to the GetDirectories (or GetFileSystemInfos) method.
Now I'm posting a tested and performance-optimized solution. It work well both on directory and file paths, and has some fault tolerance on input string.
It's optimized for "conversion" of single paths (not the entire file system), and faster than getting the entire file system tree.
Of course, if you have to renormalize the entire file system tree, you may prefer iceman's solution, but i tested on 10000 iterations on paths with medium level of deepness, and it takes just few seconds ;)
private string GetFileSystemCasing(string path)
{
if (Path.IsPathRooted(path))
{
path = path.TrimEnd(Path.DirectorySeparatorChar); // if you type c:foo instead of c:foo
try
{
string name = Path.GetFileName(path);
if (name == "") return path.ToUpper() + Path.DirectorySeparatorChar; // root reached
string parent = Path.GetDirectoryName(path); // retrieving parent of element to be corrected
parent = GetFileSystemCasing(parent); //to get correct casing on the entire string, and not only on the last element
DirectoryInfo diParent = new DirectoryInfo(parent);
FileSystemInfo[] fsiChildren = diParent.GetFileSystemInfos(name);
FileSystemInfo fsiChild = fsiChildren.First();
return fsiChild.FullName; // coming from GetFileSystemImfos() this has the correct case
}
catch (Exception ex) { Trace.TraceError(ex.Message); throw new ArgumentException("Invalid path"); }
return "";
}
else throw new ArgumentException("Absolute path needed, not relative");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…