区分 "file doesn't exist" 和 "access denied"
Distinguish between "file doesn't exist" and "access denied"
在 VBScript 中,我想知道文件是否存在:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not (fso.FileExists(file)) Then
msg = " doesn't exist."
End If
我的文件在内部网络上。
有没有办法区分:
- 文件真的不存在
- 访问被拒绝
我尝试使用 fso.OpenTextFile
但这两种情况的结果总是:Err.Number
= 5.
要区分不存在和不可访问的文件,您需要 .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
输出:
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
在 VBScript 中,我想知道文件是否存在:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not (fso.FileExists(file)) Then
msg = " doesn't exist."
End If
我的文件在内部网络上。
有没有办法区分:
- 文件真的不存在
- 访问被拒绝
我尝试使用 fso.OpenTextFile
但这两种情况的结果总是:Err.Number
= 5.
要区分不存在和不可访问的文件,您需要 .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
输出:
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