4

我在一个目录有这么长的名字并且在这么长的树上的地方工作。

而且我在外部应用程序中的文件夹路径名太长时遇到问题(我无法更改此外部应用程序,但我可以给它缩短路径名)。

我知道 Microsoft 操作系统可以缩短路径名称,例如转换C:\TooLongName\TooLongSubDirectoryC:\TooLon~1\TooLon~1.

但是我怎样才能在 C# 中做到这一点并且仍然保持中殿有效和可用?

PS:我没有使用标准FileInfoDirectoryInfo类,我只使用将发送到我无法以任何方式更改的外部应用程序的字符串。

4

1 回答 1

2

如果您无法使用 Windows 10 中内置的长路径支持,则可以使用 Win32 命令GetShortPathName。为了生成合适的路径。

class Program
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(
       [MarshalAs(UnmanagedType.LPTStr)]
       string lpszLongPath,
       [MarshalAs(UnmanagedType.LPTStr)]
       StringBuilder lpszShortPath,
       uint cchBuffer);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);

    static void Main(string[] args)
    {
        StringBuilder builder = new StringBuilder(260);
        var shortPath = GetShortPathName(@"C:\Projects\Databases\ReallllllllllllllyLOOOOOOOOOOOOOOOOOOOOOONGPATHHHHHHHHHHH\StillllllllllllllllllGOoooooooooooooooooooooooing", builder, (uint)builder.Capacity);
        Console.WriteLine(builder.ToString());
        Console.ReadKey();
    }
}

产生 C:\Projects\DATABA~1\REALLL~1\STILLL~1

于 2017-08-07T15:09:37.537 回答