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)
- Start a new Windows Forms project
- Add a button control to the default Form1
- Add a OpenFileDialog to the default Form1
- From the Project Menu, select Add Module
- 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
- 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.AppendLine()
msg.AppendFormat("Short File Name: {0}", GetShortPath(OpenFileDialog1.FileName))
MessageBox.Show(msg.ToString())
End If
End Sub
End Class
- Run the project using Ctrl+F5 and click the button.
- Navigate to a file with a long path and select ok.
- The message box with both the long and short versions of the file name should appear.
Thanks! I had been looking for an example like this for a couple of hours, but could not find it. Now I can go back to work…
Comment by Jose Torres — June 9, 2009 @ 6:45 pm
Your welcome.
Comment by Tom Shelton — June 11, 2009 @ 9:40 am
Hi Tom,
The sample you have posted is excellent. Thanks for the tip that converts the long filename to short like it was in the old days, ms-dos filenames
Thanks again.
Onur
Comment by Onur Güzel — March 4, 2010 @ 7:58 am
Hi Tom,
I’ve sent a comment, but curious of because of not seeing it displayed. Why is it missing?
PS: Thanks for great article.
Comment by Onur Güzel — March 4, 2010 @ 9:53 am
Onur – thanks for you comments
The reason your post didn’t show up right away is that I moderate the posts – to prevent spam 
Comment by Tom Shelton — March 5, 2010 @ 12:42 pm
Well, you can use long path tool for such problems, it really works good.
Comment by derikogay — January 28, 2014 @ 5:05 am