Converting Long Path Names To Short Path Names

Instead you need to actually use a p/invoke api call. Here is the code:

Imports System.Text
Imports System.Runtime.InteropServices
 
  <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
  Public Shared Function GetShortPathName(ByVal lpszLongPath As String, _
ByVal lpszShortPath As StringBuilder, ByVal cchBuffer As Integer) As Integer
  End Function
 
  Private Function ConvertLongPathToShort(ByVal longPathName As String) As String
    Dim shortNameBuffer = New StringBuilder
    Dim size As Integer = Me.GetShortPathName(longPathName, shortNameBuffer, _
shortNameBuffer.Capacity)
    If (size >= shortNameBuffer.Capacity) Then
      shortNameBuffer.Capacity = size + 1
      GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity)
    End If
    Return shortNameBuffer.ToString()
  End Function

Example:

 ConvertLongPathToShort("E:\My Documents\My Pictures\10dollarbill.jpg")

returns

E:\MYDOCU~1\MYPICT~1\10DOLL~1.JPG

I needed to do this because an open source program I am using via command-line had issues if I sent a long path/file name into it surrounded by quotes into one of its parameters. Also, the managed code calling GetShortPathName will full system permissions to call unmanaged code.

 

Tip By: David McCarter (with help from www.pinvoke.net and Igor Zinkovsky [MSFT])

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s