Tom’s Blog

October 1, 2008

Convert a Long File Name to a Short File Name

Filed under: P/Invoke,Visual Basic — Tom Shelton @ 4:26 am

Recently, on microsoft.public.dotnet.languages.vb group, help was asked in getting the code snip-it found here to work in VB2008.  Here is a conversion of the step-by-step for use in VB.NET (this should work in all versions of VB.NET)

  1. Start a new Windows Forms project
  2. Add a button control to the default Form1
  3. Add a OpenFileDialog to the default Form1
  4. From the Project Menu, select Add Module
  5. Add the following code to the new module:
    Option Explicit On
    Option Strict On
    Imports System.Text
    Module Module1
        Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
            ByVal lpszLongPath As String, _
            ByVal lpszShortPath As StringBuilder, _
            ByVal cchBuffer As Integer) As Integer
        Public Function GetShortPath(ByVal longPath As String) As String
            Dim requiredSize As Integer = GetShortPathName(longPath, Nothing, 0)
            Dim buffer As New StringBuilder(requiredSize)
            GetShortPathName(longPath, buffer, buffer.Capacity)
            Return buffer.ToString()
        End Function
    End Module
  6. Add the following code to Form1:
    Option Strict On
    Option Explicit On
    Imports System
    Imports System.Text
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            If OpenFileDialog1.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                Dim msg As New StringBuilder()
                msg.AppendFormat("Long File Name: {0}", OpenFileDialog1.FileName)
                msg.AppendFormat("Short File Name: {0}", GetShortPath(OpenFileDialog1.FileName))
            End If
        End Sub
    End Class
  7. Run the project using Ctrl+F5 and click the button.
  8. Navigate to a file with  a long path and select ok.
  9. The message box with both the long and short versions of the file name should appear.

Powered by WordPress