在C#中规范化目录名称

Tom*_*Tom 17 .net c#

这是问题,我有一堆像

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

在文件系统上,它将这些目录显示为

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

C#中是否有任何函数可以为我提供目录的文件系统名称与正确的大小写?

Ber*_*uPG 8

string FileSystemCasing = new System.IO.DirectoryInfo("H:\...").FullName;

编辑:

正如iceman指出的那样,只有当DirectoryInfo(或通常是FileSystemInfo)来自对GetDirectories(或GetFileSystemInfos)方法的调用时,FullName才会返回正确的大小写.

现在我发布了一个经过测试和性能优化的解决方案.它在目录和文件路径上都能很好地工作,并且在输入字符串上有一些容错能力.它针对单个路径(不是整个文件系统)的"转换"进行了优化,并且比获取整个文件系统树更快.当然,如果你要重新归一化整个文件系统树,你可能更喜欢冰人的解决办法,但我在10000次反复测试与深度的中等水平路径,它只需几秒钟;)

    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");
    }
Run Code Online (Sandbox Code Playgroud)

  • 我道歉。您的第一条评论似乎比您预期的更敌对,我应该放任它,而不是提出争论。当我脾气暴躁时,我真的应该远离互联网。分开道路并获得每件作品的表壳确实是一个好主意,它使痛苦的速度与可用的速度之间的区别。除非您进行修改,否则我无法批准您的答案,但这并不能阻止我批准您的其他一些答案。对不起,我很抱歉-如果您去过丹佛,我欠您一杯酒。 (2认同)