2011-08-23 284 views
30

我想檢查一個文件是否存在,如果存在,我想打開它並讀取第一行,如何檢查文件是否存在?

如果文件不存在或文件沒有內容,那麼我想要默默地失敗,不讓任何人知道發生了錯誤。

+2

您是否在任何地方搜索'vbscript file exists'? – Fionnuala

+0

@Fionnuala但這*是*谷歌的第一個結果:D;) – gordatron

回答

57

開始與此:

Set fso = CreateObject("Scripting.FileSystemObject") 
If (fso.FileExists(path)) Then 
    msg = path & " exists." 
Else 
    msg = path & " doesn't exist." 
End If 

documentation服用。

-3

現有文件夾,將FILEEXISTS

失敗
Function FileExists(strFileName) 
' Check if a file exists - returns True or False 

使用代替或補充:

Function FolderExists(strFolderPath) 
' Check if a path exists 
+0

這個答案不回答這個問題。它也不遵循格式指南。 –

+0

答案不提供任何功能代碼 –

0

對於任何人誰是尋找一種方式來觀看特定的文件在VBS存在:

Function bIsFileDownloaded(strPath, timeout) 
    Dim FSO, fileIsDownloaded 
    set FSO = CreateObject("Scripting.FileSystemObject") 
    fileIsDownloaded = false 
    limit = DateAdd("s", timeout, Now) 
    Do While Now < limit 
    If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If 
    WScript.Sleep 1000  
    Loop 
    Set FSO = Nothing 
    bIsFileDownloaded = fileIsDownloaded 
End Function 

用法:

FileName = "C:\test.txt" 
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds 

If fileIsDownloaded Then 
    WScript.Echo Now & " File is Downloaded: " & FileName 
Else 
    WScript.Echo Now & " Timeout, file not found: " & FileName 
End If