How to separate file name and path (QTP, VBScript)

Posted by Albert Gareev on Oct 25, 2009 | Categories: File System OperationsHow to

Parent page: Service Functions – System (QTP, VBScript)

Use FileSystemObject.GetFile method to obtain a File object.
Argument should be a full path string.

Set FSO = CreateObject(“Scripting.FileSystemObject”)

Check if the file exists first.

When to use it? There is a variety of utility tasks related to it: get parent folder, create another file in the same folder, create another file with the same name, etc.

Does file format matter? No. It could be text file, excel spreadsheet, bitmap, binary file, – anything. Just make sure you pass into both filename and extension.

Note. Always release the object you created when you no longer need it. If you don’t do that in the long run it’ll cause you memory leakage problem.

sFileName = "C:\TEMP\Log145473.txt"

Set objFile = FSO.GetFile(sFileName)
sName = objFile.Name
sPath = objFile.Path
sPath = Left(sPath, Len(sPath)-Len(sName))
Set objFile = Nothing
Set FSO = Nothing

'sName contains "Log145473.txt"
'sPath contains "C:\TEMP\"

  • 3 responses to "How to separate file name and path (QTP, VBScript)"

  • Kristine
    12th October 2014 at 2:59

    That is a really good tip.
    Short but very accurate information… Thank you for sharing this one.

  • mike
    24th April 2015 at 11:16

    wouldn’t it just be easier to simply use:

    sPath = objFile.ParentFolder
    ‘sPath = “C:\TEMP”

    – or –

    sPath = Replace(objFile.Path, objFile.Name, “”)
    ‘sPath = “C:\TEMP\”

    [Albert’s reply. If you need both file name and folder than not. Indeed, your version with Replace is elegant. But what if filename is one char, say “C:\TEMP\t”? What will be the result of replacing? ]

  • Ivan Ferrer
    6th October 2017 at 11:38

    it also works using
    where sPath can be a path+filename pointing to a nonexistent file.
    Good to extract the folder from an argument, ‘work there’ then write results.


  • Leave a Reply

    * Required
    ** Your Email is never shared

Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported
This work by Albert Gareev is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported.