How to generate unique file name (QTP, VBScript)
Parent page: Service Functions – System (QTP, VBScript)
How to generate a unique file name
if the file name already exists in the given folder
(That often happens, if you need to create a series of files or duplicate an existing file)
Description
sFileName – the “original” file name or file name template
sFolderName – parent folder (full path required)
objParameter – Dictionary object containing optional parameters.
- Prefix. If you want the file name to be preceded with some text (e.g. copy_userdata.xls) define a prefix.
- Index. If you want to define starting number in the series (e.g. userdata_100.xls) use index.
Note. The function does not generate a file. It generates a file name!
Example. Duplicate an existing file
Public Function UniqueFilename(ByVal sFileName, ByVal sFolderName, ByVal objParameter) Dim FSO, boolRC, sTypeName Dim index,prefix Dim sNewName, BaseName, Extension Set FSO = CreateObject("Scripting.FileSystemObject") 'to check if the objParameter passed is a dictionary object sTypeName = TypeName (objParameter) If sTypeName <> "Dictionary" Then Set objParameter = CreateObject("Scripting.Dictionary") End If 'retrieving and defaulting the parameters from objParameter prefix = objParameter.item("prefix") If prefix <> "" Then prefix = prefix & "_" index = objParameter.item("index") If Not IsNumeric(index) Then index = 1 'Separate filename and extension BaseName = FSO.GetBaseName(sFileName) Extension = FSO.GetExtensionName(sFileName) 'Generate filename and verify it doesn't exist Do sNewName = prefix & BaseName & "_" & Cstr(index) & "." & Extension boolRC = FSO.FileExists(sFolderName & "\" & sNewName) index = index+1 Loop Until boolRC = FALSE Set FSO = Nothing UniqueFilename = sNewName End Function