规范化在C#中的目录名目录

2023-09-03 00:45:48 作者:Cherish.(珍惜)

这里的问题,我有一堆目录,像

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

S:\ HELLO \ HI S:\ HELLO2 \音响\ HElloAgain

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

在文件系统中它显示了这些目录,

On the file system it shows these directories as

S:\你好\你好 S:\ hello2 \你好\ helloAgain

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

有没有在C#中的任何功能,这将使我有什么目录的文件系统的名称是正确的外壳?

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

推荐答案

字符串FileSystemCasing =新System.IO.DirectoryInfo(H:\ ...)。全名;

编辑:

正如冰人指出的,全名返回正确的壳体仅当DirectoryInfo的(或一般FileSystemInfo)来自调用GetDirectories(或GetFileSystemInfos)方法

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.

现在我发布一个测试和性能优化的解决方案。它的目录和文件路径做工精良两者,对输入字符串一些容错。 这对于单路径转换(而不是整个文件系统)进行了优化,并获得比整个文件系统树要快。 当然,如果你要重新规格化整个文件系统树,您可以preFER冰人的解决方案,但我测试了10000次迭代与深度中等水平的路径,它只需几秒钟;)

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");
    }