June 22, 2009

Convert path to Dos 8.3 notation using C#

I had an issue working with LogParser and spaces in my folders when generating output for charts. Although the escape character worked in the logparser console, it did not work using the API directly. A solution is to use the short path name and this solution is not really tied to logparser and really can be used anywhere where you have a problem like this. The code looks like this:
 using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

public class PathHelper
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)] string path,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
int shortPathLength);

public static string GetShortPathName(string path)
{
StringBuilder shortPath = new StringBuilder(500);
if(0 == GetShortPathName(path, shortPath, shortPath.Capacity))
{
if (Marshal.GetLastWin32Error() == 2)
{
throw new Exception("Since the file/folder doesn't exist yet, the system can't generate short name.");
}
else
{
throw new Exception("GetShortPathName Win32 error is " + Marshal.GetLastWin32Error());
}
}
return shortPath.ToString();
}
}
Then just call this method and send it your path and you should get the shorter DOS format. This is a really nice trick that has helped me on many occasions.

2 comments: