开发者

VB6: easy way to get folder name from filepath

If I have the full path of a file:

eg开发者_高级运维. c:\files\file.txt

What would be the easiest way to get the folder of this file: eg. c:\files\ ?


Use FileSystemObject.GetParentFolderName(strFullFilePath) e.g.

  Dim strFullFilePath As String
  strFullFilePath = "c:\files\file.txt"

  Dim fso
  Set fso = CreateObject("Scripting.FileSystemObject")

  MsgBox fso.GetParentFolderName(strFullFilePath)

Note this returns c:\file rather than c:\file\


You can use InStrRev for searching for the \, and Left$ for extracting the path bit:

filename = "c:\files\file.txt"
posn = InStrRev(filename, "\")
If posn > 0 Then
    pathstr = Left$(filename, posn)
Else
    pathstr = ""
End If

I'd make a function out of it for ease of use:

Function pathOfFile(fileName As String) As String
    Dim posn As Integer
    posn = InStrRev(fileName, "\")
    If posn > 0 Then
        pathOfFile = Left$(filename, posn)
    Else
        pathOfFile = ""
    End If
End Function


' GetFilenameWithoutExtension:  Return filename without extension from complete path
Public Function GetFilenameWithoutExtension(path As String) As String
    Dim pos As Integer
    Dim filename As String
    pos = InStrRev(path, "\")
    If pos > 0 Then
        filename = Mid$(path, pos + 1, Len(path))
        GetFilenameWithoutExtension = Left(filename, Len(filename) - Len(Mid$(filename, InStrRev(filename, "."), Len(filename))))
    Else
        GetFilenameWithoutExtension = ""
    End If
End Function

' GetFilenameWithExtension: Return filename with extension from complete path
Public Function GetFilenameWithExtension(path As String) As String
    Dim pos As Integer
    pos = InStrRev(path, "\")
    If pos > 0 Then
        GetFilenameWithExtension = Mid$(path, pos + 1, Len(path))
    Else
        GetFilenameWithExtension = ""
    End If
End Function


' GetDirectoryFromPathFilename: Return directory path contain filename
Public Function GetDirectoryFromPathFilename(path As String) As String
    Dim pos As Integer
    pos = InStrRev(path, "\")
    If pos > 0 Then
        GetDirectoryFromPathFilename = Left$(path, pos)
    Else
        GetDirectoryFromPathFilename = ""
    End If
End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜