How to create or delete a folder through QTP scripting?

Extending upon one of previous posts on QTP and File handling, I would quickly tell you how to handle folders with QTP.

For all the examples shown below I will assume that the file to be created/deleted is at C: drive.

How to create a folder with QTP?

Dim strDrive, strfoldername,objFSO, objFolder, strPath
strDrive = "c:" 'Drive where you want to create the folder
strfoldername="test" 'Name of the folder to be created
strPath= strDrive&strfoldername
' Create FileSystemObject. We have already seen this in the earlier post.
Set objFSO = CreateObject("Scripting.FileSystemObject")
On Error Resume Next ' Incase folder already exist
' Create a Folder, using strPath 
Set objFolder = objFSO.CreateFolder(strPath)
If err.Number = 58 then      'VB Script Run Time Error 58 -File Already exists
   msgbox "Folder  already exist  at" & strPath
 exitTest
End If
msgbox "Folder  created is at " & strPath


How to delete a folder?

Take the first 6 lines from the code above and add these lines

On Error Resume Next 'Incase folder is not found
objFSO.DeleteFolder(strPath)
If  err.Number =76 then      'VB Script Run Time Error 76 -File Not Found
     msgbox "Folder  Not Found at " & strPath
    exitTest
End If
msgbox "Folder  is deleted from " & strPath

How to find out if a folder exists on a drive?
Instead of using the err object as shown above, you can simply use .FolderExists()

If objFSO.FolderExists(strpath)= “Truethen
msgbox “Folder Already Exists”
End If

Ankur Jain

Founder at LearnQTP
Loves blogging and automation.

4 comments ↓

#1 john on 10.14.08 at 11:38

Hi Ankur,
This is Great work you are doing…
i am new to this site…also i registered via Email…But i need one help from you..can u send me Previous posts to my Mail…
my Id: access2john@live.com

Thanks in Advance…
John…

#2 Mahesh on 01.16.10 at 09:24

An attempt to combine the scripts “checking” and “creating” the folders:

Dim objFSO, objFolder, strPath
strPath= “D:\Mahesh”
‘ Create FileSystemObject. We have already seen this in the earlier post.
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
If objFSO.FolderExists(strpath)= “True”then
msgbox “Folder already exist at : ” & strPath
ELSE
Set objFolder = objFSO.CreateFolder(strPath)
msgbox “Folder is created at : ” & strPath
end if

#3 jyothi on 04.15.10 at 10:11

hi Ankur,

thank you very much for your script.
but, can you also give me the script for opening a folder
not creating a folder.

#4 tryinr to on 03.28.12 at 15:09

to open afolder u use systemutil.run and the path of the folder

Jyoti

Leave a Comment