Friday, July 29, 2005

Long and short file name conversion in c#

Hello. Here is very simple code for short to long and long to short file names conversion.

Short to long:

using System;
using System.Runtime.InteropServices;
using System.Text;

public class _Main
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetLongPathName(
        [MarshalAs(UnmanagedType.LPTStr)]
        string path,
        [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder longPath,
        int longPathLength
        );
        
    public static void Main()
    {
        StringBuilder longPath = new StringBuilder(255);
        GetLongPathName(@"D:\MYTEMP~1\RESOUR~1\sql.txt", longPath, longPath.Capacity);
        Console.WriteLine(longPath.ToString());
    }
}

Long to short:

using System;
using System.Runtime.InteropServices;
using System.Text;

public class _Main
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetShortPathName(
        [MarshalAs(UnmanagedType.LPTStr)]
        string path,
        [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder shortPath,
        int shortPathLength
        );
        
    public static void Main()
    {
        StringBuilder shortPath = new StringBuilder(255);
            GetShortPathName(@"D:\My Temp\ResourseProvider\sql.txt", shortPath, shortPath.Capacity);
            Console.WriteLine(shortPath.ToString());
    }
}

Please note that file must exists on the disk. This occur because file system need to know if other files. Two long names produce same names in short form and if so file system will add unique indexes to them.