Tools Links Login

Extract File or Path

Extract either a filename or path from a fully qualified pathname.

Module

Option Explicit

Public Function ParsePath(strFullPathName As String, ReturnType As Integer, Optional StripLastBackslash) As String
'
' Returns: Either the path or filename of a fully qualified pathname.
' See below for details.
'
' Called with:
' strFullPathName - STRING (REQUIRED) - the full path and file name of interest
' If strFullPathName has a length of zero, ParsePath returns a string of zero length.
' ReturnType - INTEGER (REQUIRED) - must be one of:
' vbDirectory (16) - returns the directory part of strFullPathName
' vbNormal (0) - returns the filename part of strFullPathName
' Anything else returns the full path name, which means that nothing really happens...
' StripLastBackslash - VARIANT(Boolean) (OPTIONAL) - TRUE to remove the last backslash,
' FALSE to leave it. Defaults to FALSE. Assumes that TRUE returns -1, and FALSE
' returns 0.
'
' Dependencies: None
'
'
    Dim strTemp As String, intX As Integer, strPathName As String, strFileName As String

    If IsMissing(StripLastBackslash) Then StripLastBackslash = False
    If Len(strFullPathName) > 0 Then
        strTemp = ""
        intX = Len(strFullPathName)
        Do While strTemp <> "\"
            strTemp = Mid(strFullPathName, intX, 1)
            If strTemp = "\" Then
                strPathName = Left(strFullPathName, intX + StripLastBackslash)
                strFileName = Right(strFullPathName, Len(strFullPathName) - intX)
            End If
            intX = intX - 1
        Loop

        Select Case ReturnType
        Case vbDirectory
            ParsePath = strPathName
        Case vbNormal
            ParsePath = strFileName
        Case Else
            ParsePath = strFullPathName
            ' As an alternative, you could do
            ' ParsePath = ""
        End Select
    Else
    ' You should never end up here, but if the pathname passed is
    ' a zero-length string you will, so...
        ParsePath = ""
    End If

End Function

Usage

Option Explicit

Private Sub Command1_Click()
    MsgBox ParsePath("c:\windows\calc.exe", vbDirectory, True)
End Sub

About this post

Posted: 2019-09-29
By: CharlesCassidy
Viewed: 201 times

Categories

Visual Basic 6

Attachments

No attachments for this post

Special Instructions

This code originally appeared on AndreaVB.com, and has been republished here with the permission of Andrea Tincani.


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.