如何在Visual Basic脚本中确定路径是相对路径还是绝对路径.
在VBA中,我将调用Win32 Api函数PathIsRelative
Private Declare Function PathIsRelative Lib "shlwapi" _
Alias "PathIsRelativeA" _
(ByVal pszPath As String) As Long
Run Code Online (Sandbox Code Playgroud)
但是,无法从VBS调用DLL,因此我无法使用Win32 Api.
勒内
晚了,但根据 Helen 评论引用的 Microsoft命名文件、路径和命名空间页面,如果满足以下条件,路径就是绝对路径:
- 任何格式的 UNC 名称,始终以两个反斜杠字符 ("
\\") 开头。- 带反斜杠的磁盘指示符,例如“
C:\”或“d:\”。- 单个反斜杠,例如“
\directory”或“\file.txt”。
否则,根据页面,路径是相对的。
最多要在这里检查前三个字符(检查路径是否有效,即其项目不包含非法字符或不是像 这样的保留名称CON)似乎超出了范围。
这是我的两分钱:
Function isAbsolutePath(path)
isAbsolutePath = True
Dim first : first = UCase(Left(path, 1))
Dim secondNthird : secondNthird = UCase(Mid(path, 2, 2))
If first > "A" and first < "Z" and secondNthird = ":\" Then Exit Function
If first = "\" Then Exit Function
isAbsolutePath = False
End Function
Run Code Online (Sandbox Code Playgroud)
测试代码:
Function IIf(clause, thenValue, elseValue)
If CBool(clause) Then
IIf = thenValue
Else
IIf = elseValue
End If
End Function
For Each path in Array ( _
"C:\Test1", _
"D:\Test2\", _
"3:\Test4", _
"CD:\Test5", _
"\\Test6\", _
"\Test7", _
"Test8", _
".\Test9\", _
"..\Test10" _
)
Response.Write path & ": " & IIf(isAbsolutePath(path), "absolute", "relative") & "</br>"
Next
Run Code Online (Sandbox Code Playgroud)
输出:
C:\Test1: absolute
D:\Test2\: absolute
3:\Test4: relative
CD:\Test5: relative
\\Test6\: absolute
\Test7: absolute
Test8: relative
.\Test9\: relative
..\Test10: relative
Run Code Online (Sandbox Code Playgroud)
当然,如上所述,您必须确保接下来您的路径是有效的(3:\Test4相对但非法)。