
Short Path Name in VB.NET?
Quote:
> Chris,
> You have to change the longs to integers in vb.net. Here is how
> declare the api now.
> Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA"
_
> (ByVal lpszLongPath As String, ByVal lpszShortPath As String, _
> ByVal cchBuffer As Integer) As Integer
Sorry, but you really should not use the Alias in .NET for the A/W
functions.... It makes much more sense to let the runtime determine the
correct function - you get better performance on the NT side of things
because it doesn't have to do all the useless Unicode-Ansi conversions...
Further, this function fills a buffer so you should not be passing in a
String type - this also forces the runtime to do extra work because strings
are immutable objects in .NET. You should use System.Text.StringBuilder
anytime your passing a buffer to be filled by the API call. So, here is the
best way to do this in .NET:
Declare Auto Function GetShortPathName Lib "kernel32" _
(ByVal lpszLongPath As String,
ByVal lpszShortPath As System.Text.StringBuilder, _
ByVal ccBuffer As Integer) As Integer
Dim strPath As String = Application.StartupPath
Dim strShortPath As New System.Text.StringBuilder(260) ' make it MAX_PATH
long...
GetShortPath(strPath, strShortPath, strShortPath.Capacity)
TextBox1.Text = strShortPath.ToString()
By the way, you should probably check the return value... If the function is
successful, the return value is the number of characters, not including the
null terminator, written to the buffer. If the function fails because your
buffer is to small, it returns the size of the needed buffer, so if the
return value is greater then strShortPath.Capacity, then you need to
increase the size of the StringBuilder. If the function fails for anyother
reason, it returns 0.
Tom Shelton
Quote:
> How to use it.
> Dim strPath As String = Application.StartupPath
> Dim strShortPath As String = Space(100)
> GetShortPathName(strPath, strShortPath, 100)
> TextBox1.Text = strShortPath
> Ken
> --------------
> > Anyone know how to return the short path name of a file or
> > folder in VB.NET
> > I tried using the old VB way with an API call (see below),
> > but this does not seem to work.
> > Private Declare Function GetShortPathNameA Lib "kernel32" _
> > (ByVal lpszLongPath As String, ByVal lpszShortPath _
> > As String, ByVal cchBuffer As Long) As Long
> > Public Function GetShortPathName(LongPath As String) As
> > String
> > Dim s As String
> > Dim i As Long
> > i = Len(LongPath) + 1
> > s = String(i, 0)
> > GetShortPathNameA LongPath, s, i
> > GetShortPathName = Left$(s, InStr(s, Chr$(0)) - 1)
> > End Function