views:

1306

answers:

2

looking for the standard bug-proofed way to convert "long names" such as "C:\Documents and settings" to their equivalent "short names" "C:\DOCUME~1"

I need this to run an external process from withing my C# app. It fails if I feed it with paths in the "long name".

+4  A: 

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();
    }
David Arno
+1 im just integrating an exe that only works with shortpaths (due to an internal bug)
Sam Saffron
+2  A: 

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"
ZombieSheep
It works. Do you have any explanation or documentation that explains what happens?
Hanan
Not really. It's just (reasonably) standard behaviour for modern apps to accept arguments with spaces if the string is delimited with quotes...
ZombieSheep
You need the quotes because the path is basically a command line option, and space is the delimiter for command line options. If you use a path with spaces in it, then the command line will be parsed into multiple options.Definition: "Space" - the ASCII character often mistaken for the absence of a character
Tim Long