Read text file using VBScript – 3 functions from FileSystemObject (FSO)
In order to read text file using VBScript, we can use multiple methods provided by FileSystemObject. FSO or FileSystemObject provides three functions to read a file i.e. “read“, “readline“, “readall“. These can be used as below:
You can also write text in a file using FileSystemObject(FSO) in VBScript. https://automationscript.com/how-to-write-text-file-using-vbscript/
Read – Read text File using VBScript
The read function reads data of a defined length from the whole content. Suppose there is a file with 1000 words and we call read(10), then it will read only 10 characters from the entire content. See below for how to use it.
Set fso=createobject("Scripting.FileSystemObject")
'Open the file “qtptest.txt” in writing mode.
Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True)
'write contents to the file into two newlines
qfile.Writeline "Welcome to the World of QTP"
qfile.Writeline "the file name is qtptest.txt"
'Open the file “qtptest.txt” in reading mode.
Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True)
'Read characters from the file
'Output –> “Welcome to” will be read
Msgbox qfile.Read(10)
'Close the files
qfile.Close
'Release the allocated objects
Set qfile=nothing
Set fso=nothing
ReadAll – Read text File using VBScript – all at once
ReadAll function is used when we want to read all the content from the text file. See below for how to use this function.
Set fso=createobject("Scripting.FileSystemObject")
'Open the file “qtptest.txt” in writing mode.
Set qfile=fso.OpenTextFile("C:qtptest.txt",2,True)
'write contents to the file into two newlines
qfile.Writeline "Welcome to the World of QTP"
qfile.Writeline "the file name is qtptest.txt"
'Open the file “qtptest.txt” in reading mode.
Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True)
'Read the entire contents of priously written file
Msgbox qfile.ReadAll ‘Output –> Displays the entire file.
'Close the files
qfile.Close
'Release the allocated objects
Set qfile=nothing
Set fso=nothing
ReadLine – Read text file using VBScript – line by line
ReadLine function is used when we want to read the content from a text file line by line. See below for how to use this function.
Set fso=createobject(“Scripting.FileSystemObject”)
'Open the file “qtptest.txt” in writing mode.
Set qfile=fso.OpenTextFile("C:\qtptest.txt",2,True)
'write contents to the file into two newlines
qfile.Writeline "Welcome to the World of QTP"
qfile.Writeline "the file name is qtptest.txt"
'Open the file “qtptest.txt” in reading mode.
Set qfile=fso.OpenTextFile("C:\qtptest.txt",1,True)
'Read the entire contents of priously written file
Do while qfile.AtEndOfStream <> true
Msgbox qfile.ReadLine ‘Output –> The file will be read line line by line.
Loop
'Close the files
qfile.Close
'Release the allocated objects
Set qfile=nothing
Set fso=nothing
Discover more from Automation Script
Subscribe to get the latest posts sent to your email.