Ryan McDonnell - Pursuing Web Application Zen

Getting a file’s short name (8.3 format) in .NET

Friday, July 16th, 2004 at 12:00 am

Using short file names is not something that should be needed anymore, probably violates most “best practices“ and will likely be deprecated in the future. I assume this is why Microsoft did not provide an easy method for finding a file’s short name with the .NET Framework. Unfortunately, while writing an interface to an older, poorly written application, I needed to supply the short name for some files. The code below outlines how to do this. Usage should be self-explanatory. The System.Runtime.InteropServices and System.Text classes will need to be imported.

Public Class Interop    <DllImport(“kernel32.dll”, SetLastError:=True, CharSet:=CharSet.Auto)> _
    Public Shared Function GetShortPathName(ByVal longPath As String, <MarshalAs(UnmanagedType.LPTStr)> ByVal ShortPath As StringBuilder, <MarshalAs(UnmanagedType.U4)> ByVal bufferSize As Integer) As Integer
    End Function

End Class

Private Function GetShortName(ByVal strPath As String, ByVal blnIncludePath As Boolean) As String
    Dim sb As StringBuilder = New StringBuilder(1024)
    Dim retVal As Integer = Interop.GetShortPathName(strPath, sb, 1024)
    GetShortName = sb.ToString
    If Not blnIncludePath Then
       GetShortName = Mid(GetShortName, InStrRev(GetShortName, “\”) + 1)
    End If
End Function

Comments are closed.

About Ryan McDonnell

I am a web application developer living in southern California. Commonly called a “jack of all trades” by collegues, I constantly strive to broaden my knowledge into other fields.
More about Ryan McDonnell »


 Subscribe in a reader

Quick Links & Notes

© 2004-2010 Ryan McDonnell. View my profile on LinkedIn
Some rights reserved under the Creative Commons Attribution-Share Alike 3.0 United States License.