Link to home
Start Free TrialLog in
Avatar of gthgb
gthgb

asked on

Filenames and Directorys

looking for a snippet of code to get the folder path of a file i have the full path for..
ie
"c:\this is a fake folder\document.zzz"
and i want
"c:\this is a fake folder"

or something the chdir function wont bitch at!
ASKER CERTIFIED SOLUTION
Avatar of robertlees
robertlees

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GERTJAN
GERTJAN

Here is the code to do so:


Private Const gstrSEP_DIR$ = "\"                         ' Directory separator character
Private Const gstrSEP_DRIVE$ = ":"                       ' Driver separater character, e.g., C:\
Private Const gstrSEP_DIRALT$ = "/"                      ' Alternate directory separator character
Public Path As String
Public Filename As String

Private Sub Command1_Click()
SeparatePathAndFileName "D:\BootDisk\level0\utils.cab"
End Sub

'Given a fully qualified filename, returns the path portion and the file
'   portion.

Public Sub SeparatePathAndFileName(FullPath As String, _
    Optional ByRef Path As String, _
    Optional ByRef Filename As String)

    Dim nSepPos As Long
    Dim nSepPos2 As Long
    Dim fUsingDriveSep As Boolean

    nSepPos = InStrRev(FullPath, gstrSEP_DIR)
    nSepPos2 = InStrRev(FullPath, gstrSEP_DIRALT)
    If nSepPos2 > nSepPos Then
        nSepPos = nSepPos2
    End If
    nSepPos2 = InStrRev(FullPath, gstrSEP_DRIVE)
    If nSepPos2 > nSepPos Then
        nSepPos = nSepPos2
        fUsingDriveSep = True
    End If

    If nSepPos = 0 Then
        'Separator was not found.
        Path = CurDir$
        Filename = FullPath
    Else
        If fUsingDriveSep Then
            Path = Left$(FullPath, nSepPos)
        Else
            Path = Left$(FullPath, nSepPos - 1)
        End If
        Filename = Mid$(FullPath, nSepPos + 1)
    End If
End Sub
Dir ("c:\wherever\somewhereelse\aFile.txt") will return just the file name: 'myFile.txt'. Sine you need the path, not the file name, you can remove the file name string from the complete path. Do this either by length:

myfile = "c:\wherever\somewhereelse\aFile.txt"
MsgBox Mid$(myfile, 1, Len(myfile) - Len(Dir(myfile)) - 1)

...Or simply by using a replace:

MsgBox Replace(myfile, "\" & Dir(myfile), "")

Kindest regards,
Rhaedes
here is function I've been using:

Function GetFoldersOnly(ascFullPath As String, Optional bKeepLastSlash As Boolean = False) As String
    Dim iPos As Integer
    Dim iLastPos As Integer
   
    iPos = InStr(1, ascFullPath, "\")
    Do While iPos > 0
        iLastPos = iPos
        iPos = InStr(iPos + 1, ascFullPath, "\")
    Loop
    If Not bKeepLastSlash Then iLastPos = iLastPos - 1
    GetFoldersOnly = Left(ascFullPath, iLastPos)
End Function
Avatar of gthgb

ASKER

hmm im sure i pressed that accept comment as answer button ages ago.. ahh well..
thanks to everyone that posted :)