Getting a file’s short name (8.3 format) in .NET
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