Dan*_*ler 5 c# windows path pathtoolongexception
我工作的地方,目录的名字很长,而且目录树也很长。
而且我遇到了外部应用程序中文件夹路径名太长的问题(我无法更改此外部应用程序,但我可以给它缩短的路径名)。
我知道微软操作系统可以缩短路径名,例如将C:\TooLongName\TooLongSubDirectory其转换为C:\TooLon~1\TooLon~1.
但是我怎样才能在 C# 中做到这一点并且仍然保持中殿有效和可用呢?
PS:我没有使用标准FileInfo和DirectoryInfo类,我仅使用将发送到我无法以任何方式更改的外部应用程序的字符串。
如果您无法使用 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();
}
}
Run Code Online (Sandbox Code Playgroud)
生成 C:\Projects\DATABA~1\REALLL~1\STILLL~1