0

在 VBScript 中,我想知道文件是否存在:

Set fso = CreateObject("Scripting.FileSystemObject")
If Not (fso.FileExists(file)) Then
  msg = " doesn't exist." 
End If  

我的文件在内部网络上。

有没有办法区分:

  • 文件确实不存在
  • 拒绝访问

我尝试过,fso.OpenTextFile但这两种情况的结果始终是:Err.Number= 5。

4

1 回答 1

3

要区分不存在和不可访问的文件,您需要 .FileExists.OpenTextFile:

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

Function ReadFile(p, ByRef m)
  If goFS.FileExists(p) Then
     Dim aErr
     On Error Resume Next
      Set ReadFile = goFS.OpenTextFile(p)
      aErr = Array(Err.Number, Err.Description)
     On Error GoTo 0
     If aErr(0) Then
        m = p & " - " & aErr(1)
        Set ReadFile = Nothing
     Else
        m = ""
     End If
  Else
     Set ReadFile = Nothing
     m = p & " - no such file"
  End If
End Function

Dim p, m
For Each p In Split("e:\roots.own e:\nosuchfile e:\dirsbf.tmp")
    Dim tsIn : Set tsIn = ReadFile(p, m)
    If tsIn Is Nothing Then
       WScript.Echo "fail", m
    Else
       ' read from tsIn
       tsIn.Close
       WScript.Echo "ok"
    End If
Next

输出:

cscript 35338634.vbs
fail e:\roots.own - Permission denied
fail e:\nosuchfile - no such file
ok

感谢 Ansgar 的观察,可以改进功能:

Function ReadFile(p, ByRef m)
  Dim aErr
 On Error Resume Next
  Set ReadFile = goFS.OpenTextFile(p)
  aErr = Array(Err.Number, Err.Description)
 On Error GoTo 0
  If aErr(0) Then
     m = p & " - " & aErr(1)
     Set ReadFile = Nothing
  Else
     m = ""
  End If
End Function
于 2016-02-11T12:43:46.873 回答