Learn File System Object(FSO) in UFT or QTP or VBScript Free

File System Object FSO in UFT or QTP or VBScript

Table of Contents

Share and Enjoy !

This post will cover the File System Object(FSO) in UFT. File system Object enables us to work with files like reading, write, find, search a file and folder, etc. FSO is an inbuilt object available in VBScript and VBScript driven UFT.FileSystemObject library provides various objects which allow the coders to interact with Windows File System.

FileSystemObject is a library under which we have several Objects or collections to work with files. FileSystemObject works only on the windows environment. FSO can work with WSH seamlessly.

Ads code goes here
File System Object(FSO) in UFT
File System Object(FSO) in UFT

Elements available in FSO Object Model

Object/CollectionDetails
FileSystemObjectThis is the root or main object of the class.This is the entry point to enter into the FSO.
We need to create object of FSO first in order to access several other methods and properties.It provides the below property

  • Drives

It provides several other functions like

  • CreateFolder()
  • FileExists(),
  • DrivesExists()
  • CopyFiles()
  • BuildPath()
  • CopyFolder()
  • CreateTextFile()
  • DeleteFile()
  • DeleteFolder()
  • FolderExists()
  • GetAbsolutePathName()
  • GetBaseName()
  • GetDrive()
  • GetDriveName()
  • GetExtensionName()
  • GetFile()
  • GetFileName()
  • GetFolder()
  • OpenTextFile()
  • MoveFolder()
  • MoveFile()
  • GetTempName()
  • GetParentFolderName()
  • GetSpecialFolder()
DriveThis object provides an access to underlying disk properties along with a presentation of a logical or physical drive available in the computer where
we are running the script.It provides the below properties

  • AvailableSpace
  • LastAccessed
  • RootFolder
  • DriveLetter
  • DriveType
  • Path
  • IsReady
  • FreeSpace
  • FileSystem
  • SerialNumber
  • ShareName
  • TotalSize
  • VolumeName

It does not have any methods.

Drives -Drive CollectionIt is a child of FileSystemObject denotes a collection of drives(including media drives without
removable media).It can hold information about one or more drives.It provides two properties

  • Count
  • Item

It does not have any methods.

FileIt represents a file available in the folder or a drive.We can use either FileSystemObject.GetFile() method or
Folder or Files collection to obtain a File. It provides the below properties

  • ParentFolder
  • DateCreated
  • Attributes
  • DateLastModified
  • DateLastAccessed
  • Drive
  • Name
  • Path
  • ShortName
  • ShortPath
  • Size
  • Type

It also provides the below methods

  • Copy
  • Delete
  • Move
  • OpenAsTextStream
Files-File CollectionIt is a child of Folder object and denotes a collection of Files. It provides two properties

  • Count
  • Item.

We can use Folder.Files in order to get a File

It does not provide any methods.

FolderIt represents the folder on a drive.We can get reference to a folder by using Drive.RootFolder or CreateFolder() ,
GetFolder() , and GetSpecialFolder() methods. It provides the below properties

  • Attribute
  • DateCreated
  • DateLastModified
  • DateLastAccessed
  • Drive
  • Name
  • Path
  • ShortName
  • ShortPath
  • Size
  • Type
  • Files
  • IsRootFolder
  • ParentFolder
  • SubFolders

It provides methods like-

  • Copy
  • Delete
  • Move
  • OpenAsTextStream
Folders- Collection of FoldersIt represents the collection of folder. We can get the same using Folder.SubFolders property.

This collection provides two properties

  • Count
  • Item

and a method

  • Add()

Add() method adds a subfolder to the collection.

TextStreamThis object represents the stream of text read from a file or written to a file or going to or coming from windows standard I/O.
This object has a line pointer and a character pointer.The direction of reading or writing is from top to bottom,Character by
Character or line by line.We get this object when we use File.OpenAsTestStream() or Folder.CreateTextFile() or OpenTextFile() or getStandardStream().  It provides properties or methods like Read , Write , ReadLine , WriteLine ,AtEndOfLine.
AtEndOfLine .

FileSystemObject Object

This is the foundation object to access the files and drives in Microsoft environment. The Properties and methods of FileSystemObject is given as:

FileSystemObject Properties
PropertiesComment
DrivesReturns the collection of drives including network drives available in the file system.
FileSystemObject Methods
MethodsComment
CopyFile (sourceFilePath,
destinationFilePath, overwrite)
It copies a specified file to the provided destination folder.Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes.It will throw an error if there is a same file name
already exists and overwrite flag is false.
BuildPath(path,name)This method adds the folder to the path.It can automatically add separator.It can not validate the correctness of the path.
CopyFolder (sourcePath,
destinationPath, overwrite)
It copies a specified folder to the provided destination folder.Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes.It will throw an error if there is a same folder name
already exists and overwrite flag is false.
CreateFolder (folderName)It creates a folder with the name specified and return the object as a reference.If the folder name already exist and we are
trying to create one more with the same name,It will throw an error
CreateTextFile (filename,
overwrite, unicode)
This method creates a text file in the specified folder with the specified fileName.
Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes. The default overwrite parameter is false.
The last parameter is the indication of what format the text will be stored. Default for Unicode is false.If we set it as true the whole text will be placed in Unicode.
DeleteFile (fileName,
force)
Deletes a file or files .The force parameter may be set as true.However force is an optional parameter.
By default it is false.The file/files will be deleted even if the read only attribute is set by the user for any file.
DeleteFolder (folderName,
force)
Deletes a folder or folders.The force parameter may be set as true.However force is an optional parameter.
By default it is false.The folder/folders will be deleted even if the read only attribute is set by the user for any file.
DriveExists (driveName)This method returns true if the drive letter exists otherwise it returns false.
FileExists (fileName)This method returns true if the file exists otherwise it returns false.
FolderExists (folderName)This method returns true if the folder exists otherwise it returns false.
GetAbsolutePathName
(path)
This method takes the path and returns the absolute path of the folder. Wildcard is accepted while calculating the path.
GetBaseName (filespec)This method just returns the name of the file specified in the specification by removing the path information.
GetDrive (drivespec)This method just returns the name of the drive as an object specified in the specification by removing the path information.
GetDriveName (drivespec)This method just returns the name of the drive specified in the specification by removing the path information.
GetExtensionName
(filespec)
This method returns the extension name for the file specified in the specification.
GetFile (filespec)This method return the file object specified in the file specification. File Specification may contain absolute or relative path.
GetFileName (pathspec)This method returns just the name of the file specified in the path specification.
GetFileVersion (filespec)This method returns the version of the file specified in the path specification.
GetFolder (folderspec)This method return the folder object specified in the file specification. Folder Specification may contain absolute or relative path.
GetParentFolderName
(pathspec)
This method returns just the name of the parent folder specified in the path specification.
GetSpecialFolder
(folderspec)
This method returns the Folder object with the below mentioned special permissions:
WindowsFolder (0)
SystemFolder (1)
TemporaryFolder (2)
GetTempName()This method generates a file randomly and returns the file name to perform some activities.
MoveFile (source,
destination)
Moves the file to the destination folder from source folder specified. If the destination folder already has a file with
the same name, WSH throws an error.
MoveFolder (source,
destination)
Moves the folder to the destination folder from source folder specified. If the destination folder already has a folder with
the same name, WSH throws an error.
OpenTextFile (filename,
iomode, create, format)
This method opens a file and return text as TextStreamObject. This can be used to read,write and
append to and from the file.
IOModes are:
ForReading (1)
ForWriting (2)
ForAppending (8)FileFormats are:
TristateFalse (0) to open it as ASCII,
TristateTrue (-1) to open it as Unicode
TristateUseDefault (-2) to open it using the system default format.

Drive Object

Drive object enables us to access the drives available in the system including network drives.

Drive Object Properties
PropertiesComment
AvailableSpaceReturns the available space inside the drive in bytes.
DriveLetterReturns the drive letter of the specified Drive
DriveTypeReturns the type of the drive
The type can be:
Unknown (0)
Removable (1)
Fixed (2)
Network (3)
CDRom (4)
RamDisk (5)
FileSystemReturns the file system of the Drive. The file systems can be:
FAT/NTFS/CDFS
FreeSpaceReturns the free space available in the drive
IsReadyReturns boolean True- drive is ready for operation and false is not ready for any operation.
PathReturns the path of the drive
RootFolderReturns boolean . True if the the current folder inside the drive is a Root folder.False otherwise
SerialNumberReturns the serial number of the drive. It is in decimal. This is to identify the disk volume.
ShareNameReturns the network shared name of the drive.
TotalSizeReturns the total size of the drive in bytes.
VolumeNameReturns the Volume name of the drive. We can also set the name with the same property.

File Object

File Object lets us access the files available under a Folder. File Object provides the below properties and methods:

File Object Properties
PropertiesComment
NameSets or returns the name of the file.
DriveReturns the drive letter where the file resides.
DateLastModifiedIt returns the Date and time when the file last modified.
DateLastAccessedIt returns the Date and time when the file last accessed.
DateCreatedIt returns the Date and time when the file was created.
AttributesIt returns various different attributes of a file like-
Normal (0)
ReadOnly (1)
Hidden (2)
System (4)
Volume (name) (8)
Directory (folder) (16)
Archive (32)
Alias (1024)
Compressed (2048)We can also set the following attributes:
ReadOnly
Hidden
System
Archive
ParentFolderReturns the parent folder as an Object for any file,folder.
PathReturns the absolute path of the file specified.
ShortNameReturns the shortname or DOS style file name
ShortPathReturns the short path or DOS style file path name
SizeReturns the size of the file.
TypeReturns the type of the file.
File Object Methods
MethodComment
Copy (destinationfolderpath,
boolean overwrite)
It copies a specified file to the provided destination folder.Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes.It will throw an error if there is a same file name
already exists and overwrite flag is false.
Delete (boolean force)Deletes a file forcefully if the force parameter is set as true.However force is an optional parameter.
By default it is false.The file will be deleted even if the read only attribute is set by the user.
Move(destinationFolder)Moves the file to the destination folder specified. If the destination folder already has a file with
the same name, WSH throws an error.
OpenAsTextStream(IOMode, FileFormat)This method opens a file and return text as TextStreamObject. This can be used to read,write and
append to and from the file.
IOModes are:
ForReading (1)
ForWriting (2)
ForAppending (8)FileFormats are:
TristateFalse (0) to open it as ASCII,
TristateTrue (-1) to open it as Unicode
TristateUseDefault (-2) to open it using the system default format.

Folder Object:

Folder Properties
PropertiesComment
NameSets or returns the name of the folder.
DriveReturns the drive letter where the folder resides.
FilesReturns the File collection within the folder
IsRootFolderReturns boolean True or False. True if the folder is a Root folder.
DateLastModifiedIt returns the Date and time when the folder was last modified.
DateLastAccessedIt returns the Date and time when the folder was last accessed.
DateCreatedIt returns the Date and time when the folder was created.
AttributesIt returns various different attributes of a folder like-
Normal (0)
ReadOnly (1)
Hidden (2)
System (4)
Volume (name) (8)
Directory (folder) (16)
Archive (32)
Alias (1024)
Compressed (2048)We can also set the following attributes:
ReadOnly
Hidden
System
Archive
ParentFolderReturns the parent folder as an Object
PathReturns the absolute path of the folder specified.
ShortNameReturns the shortname or DOS style folder name
ShortPathReturns the short path or DOS style folder path name
SizeReturns the size combined for files and folders inside of the folder.
TypeReturns the type of the folder.
SubFolderReturns a collection of folders residing inside the specified folder.
Folder Methods
MethodComment
Copy (destinationfolderpath,
boolean overwrite)
It copies a specified folder to the provided destination folder. Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes. It will throw an error if there is the same folder name
already exists and overwrite flag is false.
Delete (Boolean force)Deletes a folder forcefully if the force parameter is set as true. However, force is an optional parameter.
By default it is false. The file will be deleted even if the read-only attribute is set by the user for any file.
Move(destinationFolder)Moves the folder to the destination folder specified. If the destination folder already has a file with
the same name, WSH throws an error.
CreateTextFile(fileName,
overwrite, Unicode)
This method creates a text file in the specified folder with the specified fileName.

Overwrite is a boolean argument
indicating overwrite is permitted if set as Yes. The default overwrites parameter is false.

The last parameter is the indication of what format the text will be stored. The default for Unicode is false. If we set it as true the whole text will be placed in Unicode.

TextStream Object:

TextStream Object is responsible for sending and receiving the Streams to or from a file. TextStream object provides the below properties and methods:

TextStream Properties
PropertyComment
LineIt starts from line 1 and returns the current line number in the TextStream file.
ColumnIt starts from character number 1 and returns the current character number as a column from TextStream file.
AtEndOfLineReturns false if the file pointer has not reached to the end of the line
and returns true if the file pointer reached to the end of the line
AtEndOfStreamReturns false if the file pointer has not reached to the end of the TextStream
and returns true if the file pointer reached to the end of the TextStream
TextStream Methods
MethodComment
WriteBlankLines (m)writes m new line characters to the specified file as a TextStream.
WriteLine (string)Writes a newline character to the specified file as a TextStream. The String argument is optional.
If provided the method will write to the file along with the new line character.
Write (string)Writes the provided String argument to the file.
SkipLine()Skips the next line while reading from a specified file.
Skip (numOfChars)Skips the specified number of characters while reading from a specified file.
ReadLine()Reads a line from the file specified.
ReadAll()Reads the whole file as a TextStream as a single String.
Read (numOfChars)Reads the specified number of characters while reading from a specified file.
Close ()Closes an already opened file.

What is collection Object?

A collection is a set of Objects that store data as a key-value pair. Refer Dictionary Object for more details about the collection. However, we can not create our own collection objects.We need to use those which are supported by the VBScript engine only.

Like Dictionary all collection objects provide two basic properties. They are as follows:

  1. Item
  2. Count

The collection supports Enumerations on the Item property by a For Each loop but does not support methods like Exists() or RemoveAll().

It is also good to have comments in order to work with complex coding during framework development.

To work with FSO we need to create an object like below and assign the object to an instance variable. This is the starting point to work with FileSystemObject.

dim oFSO
' creating the file system object
set oFSO = CreateObject ("Scripting.FileSystemObject") 

How to Create a new text file in UFT/QTP/VBScript?

' Parameters:
' FilePath - location of the file and its name
Function CreateFile (FilePath)
' varibale that will hold the new file object
dim NewFile
' create the new text ile
set NewFile = oFSO.CreateTextFile(FilePath, True)
set CreateFile = NewFile
End Function

How to check if a specific file exists or not in QTP/UFT/VBScript?

' Parameters:
' FilePath - location of the file and its name
Function CheckFileExists (FilePath)
' check if file exist
CheckFileExists = oFSO.FileExists(FilePath)
End Function

Another approach

Option Explicit 
Dim myobjFSO,myFolder,myFile,myResult 
Set myobjFSO=WScript.CreateObject("Scripting.FilesystemObject) 
Set myFolder=myobjFSO.GetFolder("D:\\test\") 
Set myobjFSO=Nothing
myResult=false
For Each myFile in myFolder.Files
  if UCase(myFile.Name)="Test.txt" 
     myResult=true 
     Exit For
  End If 
Next
Set myFolder=Nothing 
Set myFile=Nothing
If myResult then
 msgbox "The file.exists in D:/test/folder" 
else 
 msgbox"the file does not exist in D:/test/folder"
End If

Another upgraded approach

Option Explicit 
Dim myobjFSO 
Set myobjFSO=Wscript.CreateObject("Scripting.FilesystemObject")
If myobjFSO.FileExists("D:\\test\test.txt") then
  msgbox "test.txt is present in D:\\test" 
else 
  msgbox "test.txt is not present in D:\\test" 
End if 
Set myobjFSO= nothing

How to write data to file in QTP/UFT/VBScript?

Creating a text file and writing in it is similar to reading the file. Again the text passed to the text file is TextStream object. Here we use the CreateTextFile() method to create and write text into a file.CreateTextFile() creates a fresh new Text file for editing.However, we can use the overwrite flag as true to overwrite to an existing file. In that case, we need to use the OpenTextFile() method.

File system object provides another method called WriteLine() that allows us to write a line.WriteLine has two different varieties

  • WriteLine() that appends a new line character at the end of the lines that need to be written to the file.
  • WriteLine(Str) appends the line represented by Str.

On the other hand, the File System Object also provides another method named Write(str) that allows us to write a text in the same line. The only difference is that Write() can have a non-argumented version but does not add a new line character at the end of the line.

Note- WriteLine() without a parameter will write a blank line in the output file. We may use it in a different context. But a better approach for writing a set of blank lines is to use the File System object’s WriteBlankLines() method.

Syntax-

FSO.WriteBlankLines(noOfLines)

noOfLines is an integer represents the number of blank lines to be printed.

WriteLine() or Write() Syntax-

' Parameters:
' FileRef - reference to the file
' str - data to be written to the file
Function WriteToFile (byref FileRef,str)
' write str to the text file
FileRef.WriteLine(str)
//or
FileRef.Write(str)
End Function

How to read character by character from a file in QTP/UFT/VBScript?

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:qtp.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
msgbox strCharacters
Loop

How to read a line from a file in QTP/UFT/VBScript?

' Parameters:
' FileRef - reference to the file
Function ReadLineFromFile (byref FileRef)
' read line from text file
ReadLineFromFile = FileRef.ReadLine
End Function

How to read the entire Text File using FSO in VBScript/UFT/QTP?

Reading Text file takes help of OpenTextFile() function. The function takes four inputs as arguments

They are:

  1. Which file to open?
  2. Why we are opening this file? Mode information

We have the following methods to read:

  1. ReadAll()- gets the entire file textStream into a String variable.
  2. Read()-gets one character at a time
  3. ReadLine()-gets line by line text from the file as a Stream.
' Parameters:
' FileRef - reference to the file
Function ReadTextFileTest(Filepath)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f, Msg
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(Filepath, ForReading)
ReadTextFileTest = f.Readall()
End Function

another approach:


Dim fso,f
Set fso=createobject("Scripting.filesystemobject")
set f=fso.opentextfile("C:test.txt",1)
while f.atendofline<>true
s=f.readline()
msgbox s
wend
f.close
set f=nothing
set fso=nothing
 

another approach:


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:test.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Readline
msgbox strCharacters
Loop
 

Use of Do while is best while reading from the file as :

  • We are opening a file that has some lines in it. Do ensure that.
  • We can use a close method at the end which is a best practice. Because the file’s end of file maker may not get created.

How to check if a File contains Any Data?

While working with a file or opening a file for reading purposes, we need to determine first if the file contains any data or not. To check if a file contains any data we can use AtEndOfStream property. This property returns a boolean value(True or False). True value signifies that the file contains data and False value signifies that the file does not contain any data.

How to Use AtEndOfStream Property?

Dim myFSO,strSrcFile,bOpenFile
const cForReading=1
const cForwriting=2
const cForAppending=8
Set myFSO=WScript.CreateObject("Scripting.FileSystemObject")
strSrcFile="C:\Test\log.txt" if(myFSO.FileExists(strSrcFile))then set bOpenFile=myFSO.OpenTextFile(strSrcFile,cForReading) Do while false=bOpenFile.AtEndOfStream .... ... Loop else logger.logLine("File does not exist") End If

How to close an opened file in UFT/QTP/VBScript?


' Parameters:
' FileRef - reference to the file
Function CloseFile (byref FileRef)
FileRef.close
End Function

How to open a specified file and returns an object that can be used to read from, write to, or append to the file in UFT/QTP/VBScript?

Dim myFSO,strSrcFile,bOpenFile
const cForReading=1
const cForwriting=2
const cForAppending=8
Set myFSO=WScript.CreateObject("Scripting.FileSystemObject")
strSrcFile="C:\Test\log.txt"
if(myFSO.FileExists(strSrcFile)) then
Set bOpenFile=myFSO.OpenTextFile(strSrcFile,cForAppending)
else
Set bOpenFile=myFSO.OpenTextFile(strSrcFile,cForwriting,True)
end if

You can also write the same in a function like-

' Parameters:
' FilePath - location of the file and its name
' mode options are:
' ForReading - 1
' ForWriting - 2
' ForAppending - 8
Function OpenFile (FilePath,mode)
' open the txt file and retunr the File object
set OpenFile = oFSO.OpenTextFile(FilePath, mode, True)
End Function

How to skip a line while reading lines from a File?

File system object provides SkipLine() method that allows us to skip a line while reading line by line. SkipLine() does not allow to traverse backward and it is only applicable when input file is opened for reading.While learning File System Object(FSO) in UFT , this is an important concept.

It does not need any argument and skips a single line. However, we can create a for loop to skip multiple lines.

How to copy a file in VBScript/UFT/QTP?

For copying a file FileSystemObject provides a predefined function called CopyFile(). By default, if Source File Path does not have drive information, CopyFile() will copy the file in the same directory.


' Parameters:
' FileRef - reference to the file
Sub FileCopy ( FilePathSource,FilePathDest,OverWriteFlag)
' copy source file to destination file
oFSO.CopyFile FilePathSource, FilePathDest,OverWriteFlag
End Function

It is always better to use a FileExists() method before performing any file-related operations.

FilePathSource is the source file name along with the location. Like-“C:\Test\MyReport.html”

FilePathDest is the destination file name along with the location. like-“C:\Archive\MyReport.html”

OverWriteFlag is the boolean flag that enables or disables the overwrite mechanism while copying.(In case the file already exists). We need to provide true to overwrite and false for not overwriting.

Other strategies to Copy files?

  1. If we want to copy a specific type like .html or .xls in that case the FilePathSource(source of the file) parameter will be “C:\Test\*.html” and the FilePathDest (destination of the file) will be “C:\Archive\”.
  2. if we want to copy all files from one folder to another, in that case, the FilePathSource(source of the file) parameter will be “C:\Test\*.*” and the FilePathDest (destination of the file) will be “C:\Archive\”.
  3. If the files are getting generated using some system we can use Wildcarding using Regular Expression.

Note:

  • Wildcarding is not allowed in the destination folder specification
  • We need to add the trailing backslash in the destination path just to tell WSH that it is a folder.

How to delete a file in UFT/QTP/VBScript?


' Parameters:
' FileRef - reference to the file
Sub FileDelete ( FilePath)
oFSO.DeleteFile ( FilePath)
End Function

We can also wild card characters, we can delete more than one file at a time-

Set FSOObject=CreateObject("Scripting.FileSystemObject")
FSOObject.DeleteFile "D:\Temp\*.txt",True

How to create Folder if Not Exists in UFT/QTP/VBScript?

There are two ways we can create a folder

  • Using CreateFolder() method
  • Using the Collection’s Add method
Using CreateFolder() method:

While learning File System Object(FSO) in UFT , this is an important concept.


Function ReportFolderStatus(fldr)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not (fso.FolderExists(fldr)) Then
fso.CreateFolder(fldr)
End If
End Function
ReportFolderStatus("C:\Temp")
 
Using Collections Add() method

While learning File System Object(FSO) in UFT , this is an important concept.


Option Explicit
Function ReportFolderStatus(fldr,folderToCreate)
Dim fso
Dim myObjFolder
Set fso = CreateObject("Scripting.FileSystemObject")
Set myObjFolder=fso.getFolder(fldr)
If Not (fso.FolderExists(fldr&"\&folderToCreate)) Then
myObjFolder.SubFolders.Add(folderToCreate)
End If
End Function
ReportFolderStatus("C:\Temp","Test")
 

How to delete a Folder in UFT/QTP/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


//direct delete
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.DeleteFolder("E:\FSO")
//using function
Function deleteFolder(sFolderName)
Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.DeleteFolder(sFolderName)
Set oFSO=nothing
End Function
call deleteFolder("E:\Temp")

How to copy a Folder in UFT/QTP/VBScript?

Copy a folder is a complex activity as inside the folder there can be files and folders.While learning File System Object(FSO) in UFT , this is an important concept.


//direct method
Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:\test", "C:\jvr",true
//using function
Function copyFolder(folderSrc,folderDest)
Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder folderSrc,folderDest,boolflag
End Function
call copyFolder "E:\test", "C:\jvr",true

It is the same as copy a file and the argument is pretty much the same.

It is always better to use a FileExists() method before performing any file-related operations.

  • folderSrc-is the source file name along with the location. Like-“C:\Test\”
  • folderDest-is the destination file name along with the location. like-“C:\Archive\”
  • boolflag-is the boolean flag that enables or disables the overwrite mechanism while copying.(In case the folder is already exists). We need to provide true to overwrite and false for not overwriting.

How to Count Number of Lines in a text file in VBScript/UFT/QTP?

While learning File System Object(FSO) in UFT , this is an important concept.


Function NumberOfLines(FileName)
i = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(FileName, ForReading)
Do Until objTextFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objTextFile.ReadLine
i = i +1
Loop
NumberOfLines = UBound(arrFileLines)
objTextFile.Close
End Function
msgbox NumberOfLines("C:Tempmyfile.txt")

How to get Collection(names) of Subfolders in a Folder in QTP/UFT/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


Dim a,b, c, d, e
Set a = CreateObject("Scripting.FileSystemObject")
Set b = a.GetFolder("C:\Animesh")
Set c = b.SubFolders
For Each d in c
e=e&d.name&vbnewline
Next
msgbox e
 

How to Count the Number of Files in a Folder in QTP/UFT/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


iFileCount = 0
Set objFileSysOb = CreateObject("Scripting.FileSystemObject")
Set colFolderName = objFileSysOb.GetFolder("C:Automation") ' Folder Path
Set vFiles =colFolderName.Files
For each vFileItem in vFiles
msgbox vFileItem
iFileCount = iFileCount + 1
Next
msgbox iFileCount
 

How to return a collection of Disk Drives in QTP/UFT/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


Set oFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = oFSO.Drives
For Each oDrive in colDrives
MsgBox "Drive letter: " & oDrive.DriveLetter
Next
 

How to calculate available space on a Disk Drive in QTP/UFT/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oDrive = oFSO.GetDrive("C:")
MsgBox "Available space: " & oDrive.AvailableSpace
 

How to copy an image to a folder?

While learning File System Object(FSO) in UFT , this is an important concept.

If(myFSOObject.FolderExists(pathOfFolder)=false) then
myFSOObject.CreateFolder pathOfFolder
End If
myFSOObject.CopyFile(pathOfImageFile,pathOfFolder)

How to check if a File is available or not, if available delete the File in QTP/UFT/VBScript?

While learning File System Object(FSO) in UFT , this is an important concept.


strDirectory="E:"
strFile="test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if
Folder and Sub Folder in UFT
Folder and Sub Folder in UFT

How to get Folder and Subfolder Name in QTP or UFT?

In this code, our objective is to make use of QTP(VB Script) command to get the folder and subfolder names.
Say I have drive F, under which I have a folder called V1 and under V1 I have two more subfolders called Sub Folder-v2 and v3.
Now to execute from a specific location and store result files it is very much important to get the folder name dynamically.
This article talks about the code to fetch all the information required.
The script in QTP to get Collection(names) of Subfolders in a Folder. Below script is to get Subfolders names in Folder V1Where Folder V1 is in F drive.


Dim a,b, c, d, e
Set a = CreateObject("Scripting.FileSystemObject")
Set b = a.GetFolder("F:V1")
Set c = b.SubFolders
For Each d in c
e=e&d.name&vbnewline
Next
msgbox e

How to Check if .INI file exists or not?

While learning File System Object(FSO) in UFT , this is an important concept.

if(FSOObject.FileExists("Test.ini")) then
//proceed with testing
else
//stop testing or recreate .ini file
end if

How to open a .INI file?

While learning File System Object(FSO) in UFT , this is an important concept.

FSOObjectReference.OpenTextFile(FileName,[openMode],[Create],[formattype])

FSOObjectReference is the instance of FileSystemObject,FileName is the file that needs to open along with the path.

OpenMode it is common for FSO.

ConstantMeaningvalue
ForReadingOpens or creates a file so that it can be read1
ForWritingOpens a new file and writes in it2
ForAppendingOpens an existing file and appends at the end8

Create is an optional boolean parameter. If set as True, it specifies if the file does not exist, It should be created. If set to False, it says the file does not exist and the new file is not created. The dault is false.

FormatType is also an optional parameter. It signifies the format of the file when a new file is being created.

ValueMeaning
TristateTrueOpens a file as Unicode
TristateFalseOpens a file as ASCII
TristateUseDefaultOpens the file using the operating system’s default type

How to compare two text files using VbScript or UFT?

While learning File System Object(FSO) in UFT , this is an important concept.

Public Function CompareTwoFiles(FilePath1, FilePath2)
Dim fso, myfile1, myfile2
Set fso = CreateObject(“Scripting.FileSystemObject”)
If fso.GetFile(FilePath1).Size <>fso.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set myfile1 = fso.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set myfile2 = fso.GetFile(FilePath2).OpenAsTextStream(1, 0)
CompareFiles = False
Do While myfile1.AtEndOfsotream = False
Str1 = myfile1.Read
Str2 = myfile2.Read
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles 0 Then
CompareFiles = True
Exit Do
End If
Loop
myfile1.Close()
myfile2.Close()
End Function

Return value:
The function returns 0 or False if the two files are identical, otherwise True.

Example:


myfile1 = “C:\Test\test1.txt”
myfile2 = “C:\Test\test2.txt"
If CompareFiles(myfile1, myfile2) = False Then
MsgBox "Files are having same content."
Else
MsgBox “Files are having different content.”
End If

How to count number of times a word appears in a particular file?

There is an excellant discussion on stackoverflow.  However I am providing the easiest way to do that. While learning File System Object(FSO) in UFT , this is an important concept.

Dim path, phrase, content
path    = Wscript.ScriptFullName
phrase  = "hi there\^$*+?{}.()|[]"
content = CreateObject("Scripting.FileSystemObject").OpenTextFile(path).ReadAll

Function NumberOfPhrasesInString(phrase, text, IgnoreCase)
  Dim regexpr, matches
  Set regexpr = New RegExp
  phrase = RegExEscape(phrase)
  With regexpr
    .Pattern = phrase
    .Global  = True
    .IgnoreCase = IgnoreCase
    Set matches = .Execute(text)
  End With
  NumberOfPhrasesInString = matches.count
End Function

Function RegExEscape(str)
  Dim special
  RegExEscape = str
  special = "\^$*+?{.()|[]"
  For i=1 To Len(special)
    RegExEscape = replace(RegExEscape, Mid(special, i, 1), "\" & Mid(special, i, 1))
  Next
End Function

Wscript.Echo "Number of times phrase occurs: " & NumberOfPhrasesInString(phrase, content, false)

How to get Data from a Flat file for Data-driven testing?

While learning File System Object(FSO) in UFT , this is an important concept.


dim fso,mydatafile
set fso=createObject("Scripting.FileSystemObject")
set mydatafile=fso.openTextFile("C:\testData.txt",1)
mydatafile.skipline
while mydatafile.atEndOfLine<> True
line=mydatafile.readLine
keyvaluepair=split(line,",")
key=keyvaluepair(0)
value=keyvaluepair(1)
wend

How to Get Created Date And Time Of a Particular File in QTP or In VBScript?

  • How to get created date and time of a particular file?
  • How to get the last modified date and time of a particular file?
  • How to get the last accessed date and time of a particular file?

Here is the code using VBscript’s FSO.


Set f1 = CreateObject("Scripting.FileSystemObject")
msgbox "created reference to first file object"
Set f2 = f1.GetFile("E:fak.txt")
S = "File was Created on: "&f2.DateCreated
Msgbox SOutput->File was Created on: 10/12/2008 3:45:16 PM
Set f1 = CreateObject("Scripting.FileSystemObject")
msgbox "created reference to first file object"
Set f2 = f1.GetFile("E:Lak.txt")S = "File was Last Modified on: "&f2.Datelastmodified
Msgbox SOutput->File was Last Modified on: 10/12/2008 3:51:24 PM
Set f1 = CreateObject("Scripting.FileSystemObject")
msgbox "created reference to first file object"
Set f2 = f1.GetFile("E:fak.txt")S = "File was Last Accessed on: "&f2.Datelastaccessed
Msgbox SOutput->File was Last Accessed on: 10/12/2008 3:55:15 PM

Another one is given in StackOverflow here:


Option Explicit  
Dim Myfso, path, file, LatestDate, LatestFile
Set Myfso= CreateObject("Scripting.FileSystemObject")
msgbox "created reference to first file object"
Set LatestFile= Nothing
For Each file in Myfso.GetFolder("E:Temp").Files
  If (LatestFileis Nothing) Then
    Set LatestFile= file
  ElseIf (file.DateLastModified > LatestFile.DateLastModified) Then
    Set recentFile = file
  End If
Next

If LatestFile is Nothing Then
msgbox “no latest files”
Else
msgbox “Latest file is ” & LatestFile.Name & ” ” & LatestFile.DateLastModified
End If

Similar kind of solution is given here also:


Dim Myobj, Myobj1
Set Myobj= CreateObject("Scripting.FileSystemObject")
msgbox "created reference to first file object"
Set Myobj1=obj.GetFile("C:Usersabc.vbs") 
Msgbox "ParentFolder of File is "& Myobj1. ParentFolder
Msgbox "Path of File is "& Myobj1. Path
Msgbox "Size of File is "& Myobj1. Size
Msgbox "Type of File is "& Myobj1. Type
Msgbox "DateCreated of File is "& Myobj1.DateCreated 
Msgbox "Attributes of File is "& Myobj1.Attributes
Msgbox "DateLastAccessed of File is "& Myobj1.DateLastAccessed
Msgbox "DateLastModified of File is "& Myobj1.DateLastModified
Msgbox "Name of File is" & Myobj1.Name 
Msgbox "Drive of File is "& Myobj1.Drive

Myobj1.Delete

What is not supported by FSO?

FSO does not support inserting data at the beginning of an existing file or adding some data in the middle. File System Object(FSO) in UFT also follows the same rule.

In HTML Reporting we need these tasks to be accomplished, so we need to break the task into two parts.

  1. Read the existing data into the String
  2. Write new Strings
  3. Merge and put in a text file.

Share and Enjoy !

READ  Shall We Execute Our Automation Test case in Random Order??

37 thoughts on “Learn File System Object(FSO) in UFT or QTP or VBScript Free”

  1. charlotte.tishler

    Hey there just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading properly.
    I’m not sure why but I think its a linking issue. I’ve tried it in two different
    internet browsers and both show the same outcome.

  2. I like the helpful info you provide in your articles. I will bookmark your weblog
    and check again here frequently. I’m quite certain I will learn many new stuff right
    here! Good luck for the next!

  3. Ahaa, its nice conversation about this post here around this website, I have read all that,
    so now me also commenting around this place.

  4. Pingback: Google

  5. Pingback: Google

  6. Jesusita Rosenwinkel

    Greetings! Very helpful advice within this article! It’s the little changes which will make the largest changes. Thanks a lot for sharing!

  7. It’s hard to find well-informed people on this subject, however, you appear to be you know what you’re talking
    about! Thanks

  8. Having read this I thought it was very enlightening. I appreciate you finding the time and effort to put this article together. I once again find myself spending way too much time both reading and posting comments. But so what, it was still worthwhile!

  9. Pingback: Google

  10. Pingback: Google

  11. These are actually wonderful ideas in on the topic of blogging.

    You have touched some pleasant factors here. Any way keep up wrinting.

  12. Wow, awesome blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your site is magnificent, as well as the content!

  13. I love your blog.. very nice colors & theme.

    Did you make this website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to design my own blog and
    would like to know where u got this from. thank
    you adreamoftrains website hosting services

  14. natashakilpatrick

    Does your website have a contact page? I’m having trouble locating it
    but, I’d like to shoot you an e-mail. I’ve got some suggestions
    for your blog you might be interested in hearing. Either way, great site and
    I look forward to seeing it develop over time.
    adreamoftrains best web hosting company

  15. Hey There. I found your blog using msn. This is an extremely well written article.I’ll be sure to bookmark it and return to read more of your useful info.Thanks for the post. I’ll definitely return.

  16. Pingback: Google

  17. Pingback: Google

  18. Pingback: Google

  19. Pingback: Google

  20. Pingback: Google

  21. Pingback: Google

  22. Pingback: Google

  23. Pingback: Google

  24. Pingback: Google

  25. Pingback: Google

  26. Pingback: Google

  27. notebook with both lined and blank pages

    Hello There. I came across your blog the usage of
    msn. That is certainly a very smartly written article.

    I’ll make certain to bookmark it and return to learn more of
    the helpful information. Thanks for your post. I’ll certainly
    comeback.

  28. I would like to to thanks for this great read!!

    I definitely enjoyed every little bit of it. I have got you saved as being a favorite to look into new stuff you post

  29. Pingback: Google

  30. Heya i am just the very first time here. I came across this
    board and that i find It truly useful & it helped me out a lot.
    I hope to offer something back and aid others like you aided me.

Leave a Comment

Your email address will not be published. Required fields are marked *