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.

4 Comments:

Anonymous Anonymous said...

Hi,
the best way I know is to use System.IO and Path class:

using System.IO;
...
myShortFileName = Path.GetFileName(myFullFileNameWithDirectoryName);

regards,
mikwoj

2:26 PM  
Blogger Shahzad said...

thanx buddy!!!!!!!!

shahzad Here its really helped me in my project.

Thank You!!!!!!!!

10:59 AM  
Blogger Unknown said...

Awesome! Just what I needed to work with some 16-bit external apps that only accept short paths. Thanks!

6:01 AM  
Anonymous Anonymous said...

Thanks !
Isn't there any pure .NET way ?
Anyway... thanks again!

7:26 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home