如何使用VB Scripting Host确定路径是相对路径还是绝对路径

6

如何在Visual Basic Script中确定路径是相对路径还是绝对路径。

在VBA中,应调用Win32 Api函数PathIsRelative。

Private Declare Function PathIsRelative Lib "shlwapi" _
    Alias "PathIsRelativeA" _
   (ByVal pszPath As String) As Long

然而,从VBS中无法调用DLL,因此我无法使用Win32 API。

René

4个回答

3
set oFSO = CREATEOBJECT("Scripting.FileSystemObject")

relativePath = ""
absolutePath = "c:\test"

MsgBox UCase(relativePath) = UCase(oFSO.GetAbsolutePathName(relativePath))
MsgBox UCase(absolutePath) = UCase(oFSO.GetAbsolutePathName(absolutePath))

我不明白这怎么是对问题的回答? - Spike0xff

1
晚了一些,但根据 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

测试代码:

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 是相对但非法的)。

-1
dim position
position = InStr("your-path", ":")

If position > 0 Then
  ''# absolute path
else
  ''# relative path
end if

我应该指出,分号和双斜杠在Java/C/C++等编程语言中都是常见的。 - René Nyffenegger
5
仅检查是否存在冒号是不够的。例如,C:\file.txt 是完整路径,而 C:file.txt 则是相对路径(请参见 http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#fully_qualified_vs._relative_paths)。 - Helen
@Helen:非常有用的信息,谢谢。但是我没搞清楚这个路径和哪里有关系? - Sarfraz
2
C:file.txt 指的是驱动器 C 上当前文件夹中的 file.txt 文件。同样地,C:folder\file.txt 指的是当前文件夹下 folder 子文件夹中的文件;C:..\file.txt 则指向当前文件夹的父文件夹中的文件,以此类推。 - Helen
1
\\some\share\file.txt is another absolute path which does not contain a : - bacar

-1
也许这样看起来会更好:
FUNCTION IsPathAbsolute( testedPath)

set oFSO = CREATEOBJECT("Scripting.FileSystemObject")

IsPathAbsolute = UCASE( testedPath) = UCASE( oFSO.GetAbsolutePathName( testedPath))

2
无法可靠地工作,因为GetAbsolutePathName也会规范化路径,例如C:\foo\..\bar将被规范化为C:\bar - peterchen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接