How do I determine if a path is relative 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é
In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.
A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With