Extracting Path / Filename from a String

This procedure takes a Windows compatible path and breaks it into the filename with extension and without extension, the extension alone, the path, and whether it's a valid file or not.

option Explicit

private Type PathInfo
    FileNamewExt as string
    FileNamewoExt as string
    FileExt as string
    FilePath as string
    FileIsValid as Boolean
End Type

private Sub ExtractInfo(Source as string, _
        ReturnInfo as PathInfo)

    Dim intCurrentPos as Integer, intFileNamePos as Integer
    Dim intFileExtPos as Integer
    
    'clear UDT passed in if there is any existing data
    ReturnInfo.FileExt = ""
    ReturnInfo.FileIsValid = false
    ReturnInfo.FileNamewExt = ""
    ReturnInfo.FileNamewoExt = ""
    ReturnInfo.FilePath = ""

    If Source <> "" then

        'get file name by finding the last slash in the string
        Do
            intCurrentPos = InStr(intCurrentPos + 1, Source, "\", _
                            vbTextCompare)
            If intCurrentPos <> 0 then
                intFileNamePos = intCurrentPos
            else
                intFileNamePos = intFileNamePos + 1
                Exit Do
            End If
        Loop
        
        'get file extension position if any
        intFileExtPos = InStr(intFileNamePos, Source, ".", _
                        vbTextCompare) + 1
        If intFileExtPos = 1 then
            Exit Sub
        End If
    
        'put data in UDT passed in
        If intFileNamePos <> 1 then
            ReturnInfo.FileNamewExt = mid(Source, intFileNamePos, _
                                      len(Source) - intFileNamePos + 1)
            ReturnInfo.FilePath = mid(Source, 1, _
                                  intFileNamePos - 2)
        End If
        If intFileNamePos <> 1 And intFileExtPos <> 1 then
            ReturnInfo.FileNamewoExt = mid(Source, intFileNamePos, _
                                       intFileExtPos - _
                                       intFileNamePos - 1)
            ReturnInfo.FileExt = mid(Source, intFileExtPos, _
                                 len(Source) - intFileExtPos + 1)
        End If
        If Dir(Source, vbArchive + vbHidden + vbNormal + _
               vbReadOnly + vbSystem) <> "" then
            ReturnInfo.FileIsValid = true
        else
            ReturnInfo.FileIsValid = false
        End If

    End If

End Sub

Download ExtractPath.Bas (2k)



Comments

  • Good Code

    Posted by Legacy on 06/18/2002 12:00am

    Originally posted by: Rodrigo Silva

    Thanks to the Net that I found this solution: I know I could not be the first in having the problem that you solved

    Reply
  • Please send me a solution

    Posted by Legacy on 05/15/2002 12:00am

    Originally posted by: Manojkumar Vattakkat

    Dear friend

    If any one of you are having an .OCX/Function for JUSTIFY A TEXT BOX in VB (JUSTIFY means both
    left and right side of paragraph should be aligned properly. you can confirm it with typing a paragraph in
    MSWORD and press JUSTIFY button of FORMATTING tool bar after selecting the para.) , Kindly send me.
    It will be a greate help for me for doing some works in Visual basic 6.

    Regards
    Manojkumar Vattakkatt

    Reply
  • Try this approach

    Posted by Legacy on 07/27/2001 12:00am

    Originally posted by: Sameeg Kader

    Function GetFilePath(filespec) As String
    
    'This would retrieve only the Path
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFilePath = fso.GetParentFolderName(filespec)
    End Function

    Function GetFileName(filespec) As String
    'This would retrieve Filename including Extension
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFileName = fso.GetFileName(filespec)
    End Function

    Function GetBaseName(filespec) As String
    'This would retrieve Filename excluding Extension
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetBaseName = fso.GetParentFolderName(filespec)
    End Function

    Function GetExtensionName(filespec) As String
    'This would retrieve on the File Extension
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetExtensionName= fso.GetFileName(filespec)
    End Function

    Reply
  • Extracting Path / Filename from a String

    Posted by Legacy on 07/24/2001 12:00am

    Originally posted by: v.udai kumar

    instead of useing InStr() function and going for a do loop, simply use InStrRev() function and replace the do loop with a single line statement.
    
    

    EXISTING
    ========
    Do
    intCurrentPos = InStr(intCurrentPos + 1, Source, "\", vbTextCompare)
    If intCurrentPos <> 0 then
    intFileNamePos = intCurrentPos
    else
    intFileNamePos = intFileNamePos + 1
    Exit Do
    End If
    Loop

    REPLACE IT WITH
    ===============
    intFileNamePos =1
    intFileNamePos = InStrRev(Source, "\") + 1

    Reply
  • Another bug

    Posted by Legacy on 05/18/2001 12:00am

    Originally posted by: Paul Groot

    This code also fails if the filename contains more than one dot (like "c:\temp\somefile.doc.zip").

    A more reliable aproach is to use FileSystemObject:

    Function GetTheBase(filespec)
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetTheBase = fso.GetBaseName(filespec)
    End Function

    Reply
  • Extracting Path / Filename from a String

    Posted by Legacy on 12/15/1999 12:00am

    Originally posted by: Jorge Patr�o

    This procedure works OK, but there are some problems:
    
    1. It does not deal with filenames without extension
    2. It does not deal with filenames like C:FILENAME.EXT

    So, I made a few changes to your code.
    To correct the first problem, I just eliminated 3 lines of code:

    If intFileExtPos = 1 Then
    'Exit Sub
    End If

    This way, if there is no extension, FileNamewoExt="" and FileNamewExt=FILENAME.

    To solve the second problem, I made little changes:
    . Introduced a new IF block to check whether there's a
    slash in the filename
    . Introduced a new variable, intCorrection, to deal with 2
    possibilities of specifying the filename:
    C:FILENAME[.EXT]
    C:\FILENAME[.EXT]

    I also added a new field to the PathInfo structure: PathIsValid is a boolean that tells if the filepath is valid or not.

    Here's the complete code:

    Option Explicit

    Private Type PathInfo
    FileNamewExt As String
    FileNamewoExt As String
    FileExt As String
    FilePath As String
    FileIsValid As Boolean
    PathIsValid As Boolean
    End Type


    Private Sub ExtractInfo(Source As String, ReturnInfo As PathInfo)

    Dim intCurrentPos As Integer, intFileNamePos As Integer
    Dim intFileExtPos, intCorrection As Integer

    'clear UDT passed in if there is any existing data
    ReturnInfo.FileExt = ""
    ReturnInfo.FileIsValid = False
    ReturnInfo.FileNamewExt = ""
    ReturnInfo.FileNamewoExt = ""
    ReturnInfo.FilePath = ""

    If Source <> "" Then

    'get file name by finding the last slash in the string
    Do
    intCurrentPos = InStr(intCurrentPos + 1, Source, "\", vbTextCompare)
    If intCurrentPos <> 0 Then
    intFileNamePos = intCurrentPos
    Else
    intFileNamePos = intFileNamePos + 1
    Exit Do
    End If
    Loop

    'get file extension position if any
    intFileExtPos = InStr(intFileNamePos, Source, ".", vbTextCompare) + 1

    If intFileNamePos = 1 Then
    ' Filename specified as C:FILENAME or C:FILENAME.EXT
    intFileNamePos = 3
    intCorrection = 1
    Else
    intCorrection = 0
    End If
    'put data in UDT passed in
    If intFileNamePos <> 1 Then
    ReturnInfo.FileNamewExt = Mid(Source, intFileNamePos, Len(Source) - intFileNamePos + 1)
    ReturnInfo.FilePath = Mid(Source, 1, intFileNamePos - 2 + intCorrection)
    End If
    If intFileNamePos <> 1 And intFileExtPos <> 1 Then
    ReturnInfo.FileNamewoExt = Mid(Source, intFileNamePos, intFileExtPos - intFileNamePos - 1)
    ReturnInfo.FileExt = Mid(Source, intFileExtPos, Len(Source) - intFileExtPos + 1)
    End If
    If Dir(Source, vbArchive + vbHidden + vbNormal + vbReadOnly + vbSystem) <> "" Then
    ReturnInfo.FileIsValid = True
    Else
    ReturnInfo.FileIsValid = False
    End If
    If Dir(ReturnInfo.FilePath, vbDirectory) <> "" Then
    ReturnInfo.PathIsValid = True
    Else
    ReturnInfo.PathIsValid = False
    End If
    End If

    End Sub


    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds