VB6:从文件路径获取文件夹名称的简便方法

时间:2011-03-21 07:39:59

标签: vb6 filepath

如果我有文件的完整路径:

eg. c:\files\file.txt

获取此文件的文件夹的最简单方法是什么:eg. c:\files\

3 个答案:

答案 0 :(得分:7)

使用FileSystemObject.GetParentFolderName(strFullFilePath),例如

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

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

  MsgBox fso.GetParentFolderName(strFullFilePath)

请注意,这会返回c:\file而不是c:\file\

答案 1 :(得分:6)

您可以使用InStrRev来搜索\,使用Left$来提取路径位:

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

为了便于使用,我会使用它来创建一个函数:

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

答案 2 :(得分:1)

' 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