Search code examples
vbscriptfile-existsfso

Distinguish between "file doesn't exist" and "access denied"


In a VBScript, I want to know if a file exists:

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

My files are on internal network.

Is there a way to distinguish:

  • file really doesn't exist
  • access denied

I try with fso.OpenTextFile but the result for these two cases is always: Err.Number = 5.


Solution

  • To distinguish between non-existing and non-accessible files you need .FileExists and .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
    

    Output:

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

    Thanks to Ansgar's observation, the function can be improved:

    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