Thursday, November 21, 2013

[C#] How to convert long file name to short one, and vice versa

Convert long file (directory) name to short one:

public static String GetShortPathName(String longPath)
{
    StringBuilder shortPath = new StringBuilder(longPath.Length + 1);

    if (0 == PathExtensions.GetShortPathName(longPath, shortPath, shortPath.Capacity))
    {
        return longPath;
    }
            
    return shortPath.ToString();
}

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);

Convert short file (directory) name to long one:

public static String GetLongPathName(String shortPath)
{
    StringBuilder longPath = new StringBuilder(1024);

    if (0 == PathExtensions.GetLongPathName(shortPath, longPath, longPath.Capacity))
    {
        return shortPath;
    }

    return longPath.ToString();
}

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern Int32 GetLongPathName(String shortPath, StringBuilder longPath, Int32 longPathLength);

Example:

String path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Internet Explorer\iexplore.exe");
Console.WriteLine("Long path:  '{0}'", path);

path = PathExtensions.GetShortPathName(path);
Console.WriteLine("Short path: '{0}'", path);
            
path = PathExtensions.GetLongPathName(path);
Console.WriteLine("Long path:  '{0}'", path);

Output:

Long path:  'C:\Program Files\Internet Explorer\iexplore.exe'
Short path: 'C:\PROGRA~1\INTERN~1\iexplore.exe'
Long path:  'C:\Program Files\Internet Explorer\iexplore.exe'

Full example on GitHub: PathExtensions.cs

2 comments:

  1. Other way is using Long Path Tool, it is really great tool to handle long path related issues..

    ReplyDelete