Friday, February 8, 2008

How to get the Short Filename to a Windows File in VB.NET

I had an application that needed to call an external exe and supply it with an input and output filename.  The problem I had was that if the filename had a space in it, the executable would give me an error.  I tried putting double quotes around the entire call, double quotes around the filenames, single quotes.  But nothing would work.  I didn't have access to the code of the executable.

What I ended up doing was to use the Short Filename.  Below is code that helped me do it.  I found it on some message board, but didn't save the reference.

    Private Const MAX_PATH As Integer = 260

    Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
    ByVal lpszLongPath As String, _
    ByVal lpszShortPath As System.Text.StringBuilder, _
    ByVal cchBuffer As Integer) As Integer

    Public Function GetShortFileName(ByVal LongPath As String) As String
        Dim ShortPath As New System.Text.StringBuilder(MAX_PATH)
        Dim BufferSize As Integer = GetShortPathName(LongPath, ShortPath, ShortPath.Capacity)
        Return ShortPath.ToString()
    End Function


Tjust call GetShortFileName with the filename you want to change and it will return the Windows Short Filename.

-- Ted

No comments: