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

Cra*_*ton 2 vb6 filepath

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

eg. c:\files\file.txt
Run Code Online (Sandbox Code Playgroud)

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

pax*_*blo 7

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

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

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

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
Run Code Online (Sandbox Code Playgroud)


Cra*_*ton 7

使用FileSystemObject.GetParentFolderName(strFullFilePath)例如

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

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

  MsgBox fso.GetParentFolderName(strFullFilePath)
Run Code Online (Sandbox Code Playgroud)

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

  • 我意识到这可能是一个无辜的事故,但你发布了一个[重复的问题](http://stackoverflow.com/q/1147123/15639),然后很快回答了你自己的问题:你的答案中的解决方案与[重复问题中的这个答案](http://stackoverflow.com/questions/1147123/how-to-extract-directory-from-a-file-path-string/1147131#1147131).我并没有指责你任​​何事情,我确定这是偶然的(重复的问题有一个可怕的标题),但我们应该关闭这个问题. (2认同)