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)= “True” then

msgbox “Folder Already Exists”

End If

Welcome new readers: Download the Free eBook!

I am Ankur Jain, the owner of LearnQTP and founder of a software organization. This site is run, maintained and updated by me and my team. Feel free to take a look around, you may want to start with What is QTP? 

You can connect with me on twitter @ajonit. 

Please enter your first name and email address below to instantly download the eBook on Optimizing QTP Scripts. In future, we will make sure you get new tips & tricks on QTP delivered direct to your email box.

You have Successfully Subscribed!

Share This