How to Check If a File Exists Using VBScript

When writing VBScript code, a programmer may need to confirm that a file exists before performing an action or invoking a function. This can be accomplished by accessing the Windows Script Host with VBScript and making use of the FileSystemObject. The best way to learn this programming technique is by following along in a step-by-step example. This is good practice for a beginning VBScript programmer.

Downloading files on computer screen
Confirming that a file exists is easy with VBScript.
credit: Ablestock.com/AbleStock.com/Getty Images

Step

Open Notepad. Click the Windows “Start” menu and type “notepad” in the search box. Select Notepad from the search results.

Step

Create a new file in Notepad. Type a few random letters into the file and save it as “C:\Temp\test.txt”. This file will be used to demonstrate the VBScript code.

Step

Create another new document in Notepad and save this file as “C:\Temp\FileCheck.vbs”. Adding a “.vbs” extension to a text file creates an executable VBScript file on a Windows computer.

Step

Copy and paste the following code into your Notepad document:

Step

Option Explicit

Step

'Set Dimension DIM fso

Step

'Set Object Set fso = CreateObject("Scripting.FileSystemObject")

Step

'Create Condition If (fso.FileExists("C:\Temp\test.txt")) Then 'Alert User WScript.Echo("File exists!") WScript.Quit() Else 'Alert User WScript.Echo("File does not exist!") End If

Step

'Exit Script WScript.Quit()

Step

Save the VBScript file that you just created and exit Notepad.

Step

Browse to the folder containing your VBScript file and double-click on "FileCheck.vbs". A message box should appear confirming: "File exists!" Select "OK" to close the message box.

Step

Rename or delete the “C:\Temp\test.txt” file you created in Step 1; then, double-click on the “FileCheck.vbs” script again. This time, the specified file does not exist and you'll see a message proclaiming, "File does not exist!" The If-Then-Else statement in your VBScript code is performing the check and alerting you to the results. Select "OK" to close the message box.