standard way to convert to short path in .net

丶灬走出姿态 提交于 2019-12-01 17:23:16

Does the external process fail even if you enclose the long file paths in quotes? That may be a simpler method, if the external app supports it.

e.g.

myExternalApp "C:\Documents And Settings\myUser\SomeData.file"
David Arno

If you are prepared to start calling out to Windows API functions, then GetShortPathName() and GetLongPathName() provide this functionality.

See 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();
    }

The trick with GetShortPathName from WinAPI works fine, but be careful when using very long paths there.

We just had an issue when calling 7zip with paths longer than MAX_PATH. GetShortPathName wasn't working if the path was too long. Just prefix it with "\?\" and then it will do the job and return correctly shortened path.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!