how can I check if a file exists?
Asked Answered
S

3

36

I want to check to see if a file exists and if it does, I want to open it and read the 1st line,

If the file doesn't exist or if the file has no contents then I want to fail silently without letting anyone know that an error occurred.

Stansbury answered 23/8, 2011 at 13:26 Comment(2)
Did you search for vbscript file exists anywhere?Nakisha
@Nakisha but this is the first result from google :D ;)Leninism
D
72

Start with this:

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

Taken from the documentation.

Definitive answered 23/8, 2011 at 13:47 Comment(0)
M
0

For anyone who is looking a way to watch a specific file to exist in 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

Usage:

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
Mess answered 14/2, 2018 at 14:2 Comment(0)
B
-3

an existing folder will FAIL with FileExists

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

use instead or in addition:

Function FolderExists(strFolderPath)
' Check if a path exists
Bats answered 5/6, 2013 at 20:29 Comment(1)
This answer does not answer the question. It also does not follow the formatting guidelines.Bowery

© 2022 - 2024 — McMap. All rights reserved.