[ACCEPTED]-standard way to convert to short path in .net-quotes

Accepted answer
Score: 23

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

See 1 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();
    }
Score: 4

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

e.g.

myExternalApp "C:\Documents And Settings\myUser\SomeData.file"
Score: 4

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

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

More Related questions