寻找标准的防错方法将"长名称"(如"C:\ Documents and settings")转换为等效的"短名称""C:\ DOCUME~1"
我需要这个来运行我的C#应用程序的外部进程.如果我用"长名称"中的路径提供它,它就会失败.
Dav*_*rno 20
如果您准备开始调用Windows API函数,则GetShortPathName()和GetLongPathName()提供此功能.
请参阅http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html
const int MAX_PATH = 255;
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)]
string path,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder shortPath,
int shortPathLength
);
private static string GetShortPath(string path) {
var shortPath = new StringBuilder(MAX_PATH);
GetShortPathName(path, shortPath, MAX_PATH);
return shortPath.ToString();
}
Run Code Online (Sandbox Code Playgroud)
即使您将长文件路径用引号引起来,外部进程也会失败吗?如果外部应用程序支持的话,这可能是一个更简单的方法。
例如
myExternalApp "C:\Documents And Settings\myUser\SomeData.file"
Run Code Online (Sandbox Code Playgroud)