如何从一个文件路径字符串中提取目录?(How to extract directory from a

2019-06-26 06:29发布

我只想从一个完全合格的名称来选择路径。

例如, C:\Newfolder\iTDC.mdb示于在文本框中。

但我想只拿C:\Newfolder ,去除iTDC.mdb

如何跳过文件?

Answer 1:

快速和肮脏

Dim sPath As String

sPath = "C:\Newfolder\iTDC.mdb"

sPath = Left(sPath, InStrRev(sPath, "\"))


Answer 2:

如果您添加到Microsoft脚本运行时参考(使用项目- >引用),那么你可以使用FileSystemObject做文件相关的操作。 例如:

Dim oFSO as New FileSystemObject

strFolder = oFSO.GetFolder(strPath)

FileSystemObject还具有用于构成路径(其他有用的方法BuildPath )和用于测试文件,文件夹等。(存在FileExistsFolderExists )。



Answer 3:

您可以使用PathRemoveFileSpec从2000年的功能,在Windows的每个版本和98这里是一个VB6实现。

Private Declare Function PathRemoveFileSpec Lib "Shlwapi" _
  Alias "PathRemoveFileSpecW" (ByVal szPath As Long) As Long

'Convert input file path to drive & directory only. (Supports UNC too) '    
Function sPathOnly(ByVal sInput As String) As String
  Dim sWorking As String
  sWorking = sInput
  If (PathRemoveFileSpec(StrPtr(sWorking)) <> 0) Then
    'Call succeeded. Trim trailing Null '
    sPathOnly = sTrimNull(sWorking)
  Else
    sPathOnly = sWorking
  End If
End Function

'Trim trailing null characters (e.g. from a string returned from an API call) '
Function sTrimNull(ByVal sIn As String) As String
  Dim iZeroCharacter As Long
  iZeroCharacter = InStr(sIn, Chr$(0))
  If iZeroCharacter > 0 Then
    sTrimNull = Left$(sIn, iZeroCharacter - 1)
  Else
    sTrimNull = sIn
  End If
End Function

我倾向于避免Microsoft脚本运行(包括FileSystemObject的)。 在我的经验,它偶尔打破用户的机器,也许是因为他们的IT部门是偏执病毒。 还有其他有用的功能在SHLWAPI.DLL,例如用于测试是否存在的文件夹或文件存在 。



Answer 4:

' 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


文章来源: How to extract directory from a file path string?
标签: vb6 path