Sunday, 27 October 2013

Working with File System in QTP



The automation script offten important to add, remove, wite,read,delete folders and files in the file system.

We are using the FSO (File System Object) object model. FSO is a collection of classes or objects to achieve this concept.

Script 1:

Write prgram to read data from text file.

Const ForReading=1
Dim fso,ts
set fso=CreateObject("Scripting.FileSystemObject")
Set ts= fso.OpenTextFile("d:\login.txt",ForReading)
while Not ts.AtEndOfStream
    print(ts.ReadLine())
Wend
Set fso=nothing
Set ts=Nothing

Explain

OpenTextFile(,1or 2,)- 1 for  Reading, 2 for writing
AtEndOFStream - Return false if not reached end of data in file
        Return true if reached end of data in file
ReadLine() - Read one line at each time


Script 2:

Write pgm for write data into text file

Const ForWriting=2
Dim fso,ts
set fso=CreeateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile("d:\login.txt",ForWriting,true)
For i=1 to 100
    ts.WriteLine("Hello")
Next
Set fso=nothing
Set ts=Nothing


Script 3:

Write pgm to print all lines which contains "hello" in the line
Const ForReading=1
dim fso,ts
set fso=CreateObject("Scripting.FileSystemObject")
Set ts=fso.OpenTextFile("D:\login.txt".ForReading)
While not ts.AtEndOFStream
    Strline=ts.ReadLine()
    if Instr(1,Strline,"Hello")>0 then
        Print(Strline)
    End if
Wend
Set fso=nothing
Set ts=Nothing


instr(1,Strline,"Hello") - Search String in the Strline from the first character abd return the value of the position of the first character where we can found the string.


Script 4:

Write the pgm to print the current folder name

Dim fso,fdr,fdrname
Set fso=CreateObject("Scripting.FileSystemObject")
Set fdr=fso.GetFolder(".")
fdrname=fdr.name
print(fso.GetAbsolutePathName(fdrname))
Set fso=nothing
Set fdr=nothing


Script 5:

write pgm to print all files in given folder

Dim fso,f1,fc,fdr
Set fso=CreateObject("Scripting.FileSystemObject")
Set fdr= fso.GelFolder("d:\testfolder")
set fc=fdr.Files
for Each f1 in fc
    print(f1.name)
Next

For Each - This for loop used when we done know the how many files present in tha folder.
If we dont know the start and End value for the loop, that time we can used For Each.


No comments:

Post a Comment