How do I determine if a path is relative or absolute with VB Scripting Host
How do I determine if a path is r开发者_开发百科elative or absolute in Visual Basic Script.
In VBA, I'd call the Win32 Api function PathIsRelative
Private Declare Function PathIsRelative Lib "shlwapi" _
Alias "PathIsRelativeA" _
(ByVal pszPath As String) As Long
However, it's not possible to call into a DLL from VBS, so I cannot use the Win32 Api.
René
set oFSO = CREATEOBJECT("Scripting.FileSystemObject")
relativePath = ""
absolutePath = "c:\test"
MsgBox UCase(relativePath) = UCase(oFSO.GetAbsolutePathName(relativePath))
MsgBox UCase(absolutePath) = UCase(oFSO.GetAbsolutePathName(absolutePath))
Late, but according to Microsoft Naming Files, Paths, and Namespaces page referenced by a Helen's comment, a path is absolute if:
- a UNC name of any format, which always start with two backslash characters ("
\\
").- A disk designator with a backslash, for example "
C:\
" or "d:\
".- A single backslash, for example, "
\directory
" or "\file.txt
".
Otherwise, according to the page, the path is relative.
At most the first three characters are to be checked here (checking if the path is valid, i.e. whose items don't contain illegal characters or aren't a reserved name like CON
) seems out of the scope.
Here's my two cents:
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
Test code:
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
Output:
C:\Test1: absolute
D:\Test2\: absolute
3:\Test4: relative
CD:\Test5: relative
\\Test6\: absolute
\Test7: absolute
Test8: relative
.\Test9\: relative
..\Test10: relative
Of course, as said, you must ensure next your path is valid (3:\Test4
is relative but illegal).
dim position
position = InStr("your-path", ":")
If position > 0 Then
''# absolute path
else
''# relative path
end if
Maybe it would look better this way:
FUNCTION IsPathAbsolute( testedPath)
set oFSO = CREATEOBJECT("Scripting.FileSystemObject")
IsPathAbsolute = UCASE( testedPath) = UCASE( oFSO.GetAbsolutePathName( testedPath))
精彩评论