How to Check If a File Exists Using VBScript

By Techwalla Contributor

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.

Step 1

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

Step 2

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 3

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 4

Copy and paste the following code into your Notepad document:Option Explicit 'Set Dimension DIM fso 'Set Object Set fso = CreateObject("Scripting.FileSystemObject") '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 'Exit Script WScript.Quit()

Step 5

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

Step 6

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 7

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.

Tips & Warnings

  • When working with VBSscript files, double-clicking on these files will launch the VBScript code. To edit a file with a .vbs extension, right-click on the file and select “Edit” from the context menu.