Sunday, April 10

File Handling in QTP - Part 2

Click here for Part-1 of this post.

Using FSO we can create, modify, delete files and folders. Here we'll cover, how to--

- Create Folder
- Write a line to file
- Append line to file
- Reading Data from existing file
- Search a particular string in a file
- Delete a file

Create Folder

Following code checks whether a folder or file exists or not. If not, then create it.

Dim oFSO, oFolder, oShell, oTxtFile, oFile
Dim strFolder, strFile

' Create File System Object
Set oFSO = CreateObject("Scripting.FileSystemObject")

'Set folder and file name
strFolder = "C:\QTPSchools"
strFile = "\abhi.txt"

' Check if strFolder folder exists. If not, create it.
If oFSO.FolderExists(strFolder).Exist = False Then
    Set oFolder = oFSO.CreateFolder(strFolder)
    Print "Folder did't exist already. Created now -  " & strFolder
End If

' Check if oFile folder exists. If not, create it.
If oFSO.FileExists(strFolder & strFile).Exist = False Then
    Set oFile = oFSO.CreateTextFile(strFolder & strFile)
    Print "File did't exist already. Created now -  " & strFolder & strFile
End If

set oFile = Nothing    'Relese object
set oFolder = Nothing    'Relese object

Write a line to file

Following code demonstrate how to open an existing file and write a line to file and close.

Set oFSO = CreateObject("Scripting.FileSystemObject")

Const ForWriting = 2
Set oTxtFile = oFSO.OpenTextFile("C:\QTPSchools\abhi.txt", ForWriting, True)
oTxtFile.WriteLine "This is the new line - ForWriting"     


Append a line to file

Const ForAppending = 8
Set oTxtFile = oFSO.OpenTextFile("C:\QTPSchools\abhi.txt", ForAppending, True)
oTxtFile.WriteLine "This is the new line - ForAppending"    

Please note that if you open file in Writing mode, all the existing data will be overridden by new data. But if you open file in Appending mode then all existing data will be preserved and new data will be appended at bottom.

Reading Data from existing file

Const ForReading = 1
Set oTxtFile = oFSO.OpenTextFile("C:\QTPSchools\abhi.txt", ForReading, True)
Print oTxtFile.Readline 'it will read first line from the file

Search a particular string in a file

Following code demonstrate how to search a particular pattern/string in file. It will print all the line in which string found.

Const ForReading = 1

Set oRegEx = CreateObject("VBScript.RegExp")
oRegEx.Pattern = "new.*" ' Enter pattern/string you want to search

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.OpenTextFile("C:\QTPSchools\abhi.txt", ForReading)

Do Until oFile.AtEndOfStream
    strSearchString = oFile.ReadLine
    Set colMatches = oRegEx.Execute(strSearchString)
    If colMatches.Count > 0 Then
        print strSearchString
    End If

Find and replace a pattern string (regular expression) in a file

Function f_ReplacePatternString(Corr_Id)
 strFilename = "C:\DIR\all_Files\try.txt"
 Const ForReading = 1
 Const ForWriting = 2
 Set oRegEx = CreateObject("VBScript.RegExp")
 oRegEx.Pattern = "requestId"":\""\d{3}"

 Set oFSO1 = CreateObject("Scripting.FileSystemObject")
 Set oFile = oFSO1.OpenTextFile(strFilename, ForReading)
 strOldString = oFile.ReadAll
 Set colMatches = oRegEx.Execute(strOldString)
 For each match in colMatches
 msgbox match.value
 strNewString = Replace(strOldString, match.value , "requestId"":""" &Corr_Id&"")
 Set oFSO1 = Nothing
 Set oFSO2 = CreateObject("Scripting.FileSystemObject")
 Set oFile = oFSO2.OpenTextFile(strFilename, ForWriting,True)
 oFile.WriteLine strNewString
End Function
Call f_ReplacePatternString("222")
Delete a file

Following code demonstrate how to delete a particular file.

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.DeleteFile("C:\QTPSchools\abhi.txt")

Access file information

   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filename)
   s = "Path: " & f.Path & vbnewline
   s = s & "Created: " & f.DateCreated & vbnewline
   s = s & "Last Accessed: " & f.DateLastAccessed & vbnewline
   s = s & "Last Modified: " & f.DateLastModified  
   ShowFileAccessInfo = s
   msgbox ShowFileAccessInfo

Here is the output - 

In case of any queries, please leave your comments.


  1. Awesome job man....

  2. Thank you for good examples

  3. I am trying to copy a file form network to the c drive on my PC. Script is running fine with a hard coded pathes but when I run the same script using parameters for sourceflocation and source destination from QT-Scripted (BPT component)- I have an error "Permission denied". Any Ideas?

  4. Hi Abhikansh,
    While creating new folder and file into it I am getting below error,
    1.Object required: 'FolderExists(...)'

    Line (15): "If oFSO.FolderExists(strFolder).Exist = False Then".

    2.Object required: 'FileExists(...)'

    Line (21): "If oFSO.FileExists(strFolder & strFile).Exist = False Then".

    Can you please let me know the reason and how to recover it.


  5. You can use the following commands and it works fine for me...

    If not oFSO.FolderExists(strFolder) Then

    If not oFSO.FileExists(strFolder & strFile) Then

  6. Hi I am Mumthaj. Could you tell me how to count words in a text file