c# - 在 C# 中规范化目录名称

标签 c# .net

问题来了,我有一堆目录,比如

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

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

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

C# 中是否有任何函数可以告诉我目录的文件系统名称是什么以及正确的大小写?

最佳答案

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

编辑:

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

现在我发布了一个经过测试和性能优化的解决方案。它在目录和文件路径上都能很好地工作,并且对输入字符串具有一定的容错能力。 它针对单个路径(不是整个文件系统)的“转换”进行了优化,并且比获取整个文件系统树更快。 当然,如果你必须重新规范化整个文件系统树,你可能更喜欢 iceman 的解决方案,但我在中等深度的路径上测试了 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");
    }

关于c# - 在 C# 中规范化目录名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1214513/

相关文章:

c# - ASP.NET MVC 3 服务器端验证因 ViewModel 中的下拉列表集合而失败

c# - 如何将点从一个网格映射到另一个网格?

c# - log4net错误呈现

c# - 如何在运行时从 .NET 应用程序更改 DTS 包中的连接字符串?

c# - XML 序列化如何知道将属性放在哪里?

c# - 获取 .NET 枚举的 Windows 本地化

c# - IHttpAsyncHandler 和 Request.Filter

c# - Dependency Injection 和具体的依赖实现

c# - 使用 Caliburn Micro 将 EventAggregator 注入(inject) ViewModel

javascript - Check Box在gridview中以行索引方式被选中