VbScript - File Checker

At times, when programming with VBScript, a programmer will want to know if a file exists prior to performing another function.

This is good programming practice and it can be accomplished by accessing the Windows Script Host via VBScript and making use of the FileSystemObject.

The program below will walk you through the steps necessary to accomplish this task and give you a real world example to learn from.

Create a file on your computer named test.txt at the following location C:\Temp\test.txt

This will be used to demonstrate the VBScript.Step 2

Open Notepad
Go to Start - All Programs - Accessories - Notepad
Save your file as C:\Temp\FileCheck.vbs

Note: Adding .vbs to any .txt file creates an executable VBScript file.

Copy Code
Copy and Paste the following code into Notepad.

Run Script
      Browse to C:\Temp\FileCheck.vbs using My Computer or Explore, depending on what you're use to.
      Double-click on VBScript file "FileCheck.vbs". You should get a message box as shown below stating that the "File exists!". Select "OK"
  
      Step 5

 File does not exist!
      Now rename or remove the following file C:\Temp\test.txt and Double-click on the FileCheck.vbs again.
      This will create a condition where the file does not exist and you should get a message box which states "File does not exist!" Select "OK"


      The If Then Else statement in the code above is doing the check and alerting you as to whether or not the file exists.


'**************************************************************
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()
'**************************************************************
Save your VBScript file and exit Notepad

Step 4  Run Script

Browse to C:\Temp\FileCheck.vbs using My Computer or Explore, depending on what you're use to.
Double-click on VBScript file "FileCheck.vbs". You should get a message box as shown below stating that the "File exists!". Select "OK"

Now rename or remove the following file C:\Temp\test.txt and Double-click on the FileCheck.vbs again.
This will create a condition where the file does not exist and you should get a message box which states "File does not exist!" Select "OK".
The If Then Else statement in the code above is doing the check and alerting you as to whether or not the file exists.

Post a Comment

Previous Post Next Post