如何从文件路径字符串中提取目录?

时间:2009-07-18 09:46:10

标签: vb6 path

我想仅从完全限定名称中选择路径。

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

但我只想C:\Newfolder删除iTDC.mdb

如何跳过文件?

4 个答案:

答案 0 :(得分:8)

快速而肮脏

Dim sPath As String

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

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

答案 1 :(得分:6)

如果添加对Microsoft Scripting Runtime的引用(使用Project-> References),则可以使用FileSystemObject执行与文件相关的操作。例如:

Dim oFSO as New FileSystemObject

strFolder = oFSO.GetFolder(strPath)

FileSystemObject还有其他有用的方法来组合路径(BuildPath)以及测试文件,文件夹等是否存在(FileExistsFolderExists

答案 2 :(得分:3)

您可以使用PathRemoveFileSpec功能,该功能适用​​于2000和98的每个Windows版本。这是一个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 Scripting Runtime(包括FileSystemObject)。根据我的经验,它偶尔会在用户计算机上崩溃,可能是因为他们的IT部门对病毒感到偏执。 shlwapi.dll中有other useful functions,例如用于测试folders existfiles exist

答案 3 :(得分:0)

' 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