Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize directory names in C#

Tags:

c#

.net

Here's the problem, I have a bunch of directories like

S:\HELLO\HI
S:\HELLO2\HI\HElloAgain

On the file system it shows these directories as

S:\hello\Hi
S:\hello2\Hi\helloAgain

Is there any function in C# that will give me what the file system name of a directory is with the proper casing?

like image 885
Tom Avatar asked Jul 31 '09 19:07

Tom


1 Answers

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");
    }
like image 184
BertuPG Avatar answered Sep 27 '22 19:09

BertuPG