如何在Visual Basic脚本中确定路径是相对路径还是绝对路径。
在VBA中,我将调用Win32 Api函数PathIsRelative
Private Declare Function PathIsRelative Lib "shlwapi" _
Alias "PathIsRelativeA" _
(ByVal pszPath As String) As Long
但是,无法从VBS调用DLL,所以我无法使用 Win32 Api。
勒
答案 0 :(得分:2)
set oFSO = CREATEOBJECT("Scripting.FileSystemObject")
relativePath = ""
absolutePath = "c:\test"
MsgBox UCase(relativePath) = UCase(oFSO.GetAbsolutePathName(relativePath))
MsgBox UCase(absolutePath) = UCase(oFSO.GetAbsolutePathName(absolutePath))
答案 1 :(得分:1)
后来,但是根据Helen的注释所引用的Microsoft Naming Files, Paths, and Namespaces 页面,如果满足以下条件,则该路径为绝对路径:
- 任何格式的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
测试代码:
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
输出:
C:\Test1: absolute
D:\Test2\: absolute
3:\Test4: relative
CD:\Test5: relative
\\Test6\: absolute
\Test7: absolute
Test8: relative
.\Test9\: relative
..\Test10: relative
当然,如前所述,您必须确保下一个路径有效(3:\Test4
是相对路径,但非法)。
答案 2 :(得分:-1)
dim position
position = InStr("your-path", ":")
If position > 0 Then
''# absolute path
else
''# relative path
end if
答案 3 :(得分:-1)
也许这样看起来会更好:
FUNCTION IsPathAbsolute( testedPath)
set oFSO = CREATEOBJECT("Scripting.FileSystemObject")
IsPathAbsolute = UCASE( testedPath) = UCASE( oFSO.GetAbsolutePathName( testedPath))