VB6: easy way to get folder name from filepath

自闭症网瘾萝莉.ら 提交于 2019-12-12 17:24:34

问题


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\ ?


回答1:


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



回答2:


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\




回答3:


' 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


来源:https://stackoverflow.com/questions/5374962/vb6-easy-way-to-get-folder-name-from-filepath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!