c# - 如何在 Windows 上获取区分大小写的路径?

标签 c# .net filepath

我需要知道哪个是给定路径的真实路径。

例如:

真实路径是:d:\src\File.txt
用户给我:D:\src\file.txt
结果我需要:d:\src\File.txt

最佳答案

你可以使用这个函数:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint GetLongPathName(string ShortPath, StringBuilder sb, int buffer);

[DllImport("kernel32.dll")]
static extern uint GetShortPathName(string longpath, StringBuilder sb, int buffer); 

protected static string GetWindowsPhysicalPath(string path)
{
        StringBuilder builder = new StringBuilder(255);

        // names with long extension can cause the short name to be actually larger than
        // the long name.
        GetShortPathName(path, builder, builder.Capacity);

        path = builder.ToString();

        uint result = GetLongPathName(path, builder, builder.Capacity);

        if (result > 0 && result < builder.Capacity)
        {
            //Success retrieved long file name
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        if (result > 0)
        {
            //Need more capacity in the buffer
            //specified in the result variable
            builder = new StringBuilder((int)result);
            result = GetLongPathName(path, builder, builder.Capacity);
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        return null;
}

关于c# - 如何在 Windows 上获取区分大小写的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763117/

相关文章:

c# - 何时在 C# 中使用 Value 关键字

c# - UWP Commandbar 到右侧

c# - -10 在 1.5 × 10^-45 和 3.4 × 10^38 之间吗?

java - 如何在我的 Java 代码中找到文件

c# - 匿名委托(delegate) - 使用对象集合搜索属性

c# - "Anonymous Recursion"在 .NET 中有效吗?它在单声道

c# - 使 dataGridView 大小适合行和列的总大小

c# - 如何阻止 VS2015 将 my.csproj 转换为 .sqlproj?

java - getAbsolutePath 忽略某些文件夹

c++ - 你如何在 Xcode 6 中更新文件路径