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])
Discover more from dotNetTips.com
Subscribe to get the latest posts sent to your email.
