在VBScript中,我想知道文件是否存在:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not (fso.FileExists(file)) Then
msg = " doesn't exist."
End If
我的文件在内部网络上。
有没有办法区分:
我尝试使用fso.OpenTextFile
,但这两种情况的结果始终为:Err.Number
= 5.
答案 0 :(得分: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