Friday, May 2, 2008

VBScript - File Read and Write

I have developed few projects using Visual Basic. But I do not have much scripting in Visual Basic Script (VBS). In VB, the file handling functions are different than VBScript. We need to use FileSystemObject for file handling. Below I have given two code snippets to read and write into text files. This code can be used into Quick Test Professional also.

Reading a Text file



Const ForReading = 1, ForWriting = 2

FileName = "D:\VBs\Mysamples\1create.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(FileName) Then

Set objTextFile = objFSO.OpenTextFile(FileName, ForReading)

Do while Not objTextFile.AtEndOfStream
sLine = objTextFile.ReadLine
Wscript.Echo sLine
loop

End If

objTextFile.Close

Set objFile = Nothing
Set objFSO = Nothing


Writing to a Text file


Const ForAppending = 8
FileName = "D:\VB\Mysamples\1create.txt"

Set objFSO = CreateObject("scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (FileName, ForAppending, True)

For iIndex=1 to 10
objTextFile.WriteLine(iIndex)
Next

objTextFile.Close

Set objTextFile = Nothing
Set objFSO = Nothing

No comments: