Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A 'SplitPath' for VBasic, splitting file name and path.

Folders and Files

A 'SplitPath' for VBasic, splitting file name and path.

by  jnicks  Posted    (Edited  )
Many BASIC programmers have to examine a file name string and separate file name drom path. The routine splitpath is common in many languages but missing from in Visual Basic.

The usual way to do this in VB is to start at the far end of the string end and look for a reverse solidus, '\', or backslash. This is a slow and more complex than necessary.

Our process is simple, we get the correct full path\name and subtract the file name.

[ul]
[li]DIR returns the long file name.
[li]GetFullPathName is a win 32 function that returns long path and file name.
[li]If we remove the number of characters at the end of the full path and file name from GetFullPathName we have the path, and we already have the file name, from DIR
[li]Return path and file name separately
[/ul]
Done.

No loops. Fast.


Code:
Attribute VB_Name = "Module1"
DefLng A-Z
Declare Function GetFullPathName Lib "kernel32" Alias "GetFullPathNameA" (ByVal lpFileName As String, ByVal nBufferLength As Long, ByVal lpBuffer As String, ByVal lpFilePart As String) As Long
Sub main()
  ret = splitpath("c:\autoexec.bat", path$, longfilnam$)
  MsgBox path$
End Sub


Function splitpath(fil$, path$, longfilnam$)
Static buf As String * 261, dummy As String * 20

' returns -1 as Long for error

  path$ = "": splitpath = -1
  
  longfilnam$ = Dir$(fil$)

  If 0 = Len(longfilnam$) Then Exit Function
  
  k = GetFullPathName(fil$ + Chr$(0), 260, buf, dummy)

  If k Then _
    path$ = Left(buf, k - Len(longfilnam$)): _
    splitpath = 0

End Function
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top