tags:

views:

456

answers:

3

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?

A: 

This should do it:

System.IO.Directory.GetFiles("...");
John Fisher
+1  A: 
Partha Choudhury
He's asking for the casing as stored on the file system, not necessarily TitleCasing.
Iceman
+1  A: 

Here you go:

static string NormalizeFolder(string path)
{
  DirectoryInfo dir = new DirectoryInfo(path);

  return dir.Root
    .GetDirectories("*", SearchOption.AllDirectories)
    .First(d => d.FullName.ToUpper() == path.ToUpper())
    .FullName;      
}

Update: Yeah, that would be ridiculously slow if you're doing it more than once. In that case, you'll want to save the results using something like this:

class DirectoryNormalizer
{
  private Dictionary<string, string> directories;

  public DirectoryNormalizer()
  {
    directories = new Dictionary<string, string>();
  }

  public string Normalize(string path)
  {
    DirectoryInfo dir = new DirectoryInfo(path);
    if (!dir.Exists)
      return path; //maybe you'd rather return string.Empty here?
    if (directories.ContainsKey(dir.FullName.ToUpper()))
      return directories[dir.FullName.ToUpper()];
    foreach (DirectoryInfo d in dir.Root.GetDirectories("*", SearchOption.AllDirectories))
    {
      if (directories.ContainsKey(d.FullName.ToUpper()))
      {
        directories[d.FullName.ToUpper()] = d.FullName;
      }
      else
      {
        directories.Add(d.FullName.ToUpper(), d.FullName);
      }
    }
    return directories[dir.FullName.ToUpper()];
  }
}
Iceman
this works but it is PAINFULLY slow since it does a full system scan for search directory and I have over 100 directories to normalize
Tom
@Tom, see my update. I should have thought about multiple directories initially.
Iceman