如何从文件路径字符串中提取目录?
Posted
技术标签:
【中文标题】如何从文件路径字符串中提取目录?【英文标题】:How to extract directory from a file path string? 【发布时间】:2009-07-18 09:46:09 【问题描述】:我只想从完全限定名称中选择路径。
例如,C:\Newfolder\iTDC.mdb
显示在文本框中。
但我只想取C:\Newfolder
,去掉iTDC.mdb
。
如何跳过文件?
【问题讨论】:
【参考方案1】:又快又脏
Dim sPath As String
sPath = "C:\Newfolder\iTDC.mdb"
sPath = Left(sPath, InStrRev(sPath, "\"))
【讨论】:
请注意,如果字符串中没有反斜杠,代码将引发错误。【参考方案2】:如果您添加了对 Microsoft Scripting Runtime 的引用(使用 Project->References),那么您可以使用FileSystemObject
进行文件相关操作。例如:
Dim oFSO as New FileSystemObject
strFolder = oFSO.GetFolder(strPath)
FileSystemObject
还具有其他有用的方法来组合路径 (BuildPath
) 和测试文件、文件夹等是否存在(FileExists
、FolderExists
)。
【讨论】:
【参考方案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 exist 还是files exist。
【讨论】:
【参考方案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
【讨论】:
以上是关于如何从文件路径字符串中提取目录?的主要内容,如果未能解决你的问题,请参考以下文章