FSO is the abbreviation of FileSystemObject or , which is a built-in component of IIS for manipulating disks, folders, or text files. There are many objects, methods and properties in FSO. Here we list common ones in the example way. Note: "FileSystemObject User Guide" and "Scripting Runtime Library Reference" in "VBScript Language Reference" or "JScript Language Reference" are the complete references for FileSystemObject given by Microsoft.
FSO cannot operate binary files. To operate binary files, use:.
The following is a detailed introduction to FileSystemObject, which is a child object.
Preface
I have been learning VBScript recently and there are many related tutorials online, but most of the objects are explained in ASP, which is very depressed for students who have not studied ASP. Therefore, I plan to write down the properties and methods commonly used in learning FileSystemObject and TextStream for everyone to learn. If there are any inappropriate points, please point them out.
Note: All scripts have been tested in QTP 9.0.
FileSystemObject Object Overview
The function of the FileSystemObject object: provides access to the computer file system, which allows us to manipulate text files, folders and drives in the code. The FileSystemObject object provides a property and a series of methods that can be used to manipulate some subordinate objects implemented by the FileSystemObject object. Here is a complete summary of the content, and then introduce each subordinate object.
1. Properties of FileSystemObject
The FileSystemObject object has only one property, which is used to get a list of all valid drives on the current machine, as shown in Table 1:
Table 1 Properties and descriptions of FileSystemObject object |
|
property |
illustrate |
Drivers |
Return to the list of available drives on the local computer |
'You can get the following scriptFileSystemObjectofDriversproperty Set objFSO = CreateObject ("") Set colDrivers =
As you have seen, the FileSystemObject object contains a property - Drives, which returns a collection of all available drives on the local computer.
Each entry in the Drives collection is a Drive object. The properties of the Drive object are shown in Table 2:
Table 2 Properties and descriptions of Drive objects |
|
method |
illustrate |
AvailableSpave |
Referring to account quotas and/or other limitations, return the size of space available to that user on the drive |
DriveLetter |
Return the letter of the drive |
DriveType |
Returns the drive type. The return values can be Unknown(0), Removeable(1), Fixed(2), Network(3), CDRom(4) and RamDisk(5). However, it should be noted that the current version does not support predefined constants Network, and decimal 3 must be used instead |
FileSystem |
Returns the type of the drive file system. Return values include "FAT", "NTFS" and "CDFS" |
FreeSpace |
Returns the total amount of remaining space available on the drive |
IsReady |
Return a boolean value to indicate if the drive is ready |
Path |
Returns a drive path composed of drive letters and colons, i.e. "C:" |
RootFolder |
Returns the Folder object of the representative drive root folder |
SerialNumber |
Returns a decimal sequence number used to identify the disk volume |
ShareName |
If it is a network drive, return the network share name of the drive |
TotalSize |
Returns the total capacity of the drive in bytes |
VolumeName |
Set or return the local drive volume name |
Therefore, by using the Drive objects in the Drives collection, a drive list can be generated on the server, which is more efficient than a method of determining whether a drive exists by checking each possible drive letter. We can also get information about the drive.
Example:
' createFileSystemObjectObject Set objFSO = CreateObject("") ' createDrivesgather,and assign tocolDrives Set colDrives = 'Travel over Drives collection For Each objDrive in colDrives 'Determine if the drive is ready If Then msg = "The name of the drive is:" & & " " msg =msg & "Type of drive file system:" & &" " msg = msg & "Total drive capacity:" & int(/(1024*1024*1024)) & "G " msg = msg & "Total amount of space remaining:" & int(/(1024*1024*1024)) & "G " End If Next micDone ,"Traveling through Drives Collection",msg
Note: There is something to pay attention to before running this program on the system. If there is no disk in drive A, or there is no CD in drive A, you will get an error message: "Disk Not Ready". In addition to the DriveLetter attribute and DriveType attribute, the page can be protected by checking the IsReady attribute of each drive before using other attributes and methods.
2. Methods of FileSystemObject
1. Drive-related methods
Table 3. Methods and descriptions related to drives |
|
method |
illustrate |
DriveExists(drivespec) |
Return True if the drive specified in drivespec exists, otherwise return False. drivespec parameter can be a drive letter, or the complete absolute path to a file or folder |
GetDrive(drivespec) |
Returns the Drive object corresponding to the drive specified by drivespec. drivespec can contain colons, path separators or network share names, namely: "C", "C:", "C:" and "/machinesharename" |
GetDriveName(drivespec) |
Returns the name of the drive specified by drivespec using a string. drivespec parameter must be the absolute path to the file or folder, or just the drive letter, for example: "c:" or "c" |
Use of DriveExists
Method name: DriveExists(drivespec)
Description: Returns True if the drive specified in drivespec exists, otherwise returns False. The drivespec parameter can be a drive letter, or the complete absolute path to a file or folder.
Example:
' createFileSystemObjectObject Set objFSO = CreateObject ("") For intCode = 65 To 90 'ANSI codes for 'A' to 'Z' strLetter = Chr(intCode) 'Chr:Return with specified ANSI Characters corresponding to the character code。 If (strLetter) Then 'Determine whether the corresponding drive letter exists,If the output exists micDone,"Show Drive”,” Found drive " & strLetter End If Next
Also, if the drive, folder, or file to be accessed is known. You can use GetDrive, GetFolder, GetSpecialFolder, and GetFile methods directly on it.
2. Methods and properties related to folders
How to use FileSystemObject object to operate folders:
Table 4 Methods and descriptions related to folders |
|
method |
illustrate |
BuildPath(path,name) |
Add a file or folder named name on the existing path path. If necessary, add a path separator ' ' |
CopyFolder(source,destination,overwrite) |
Copy one or more folders from the specified source folder source (can contain wildcards) to the specified destination folder destination, including all files in the source folder. If source contains wildcards or destination is the path delimiter (''), then destination is considered to be the folder where the copy of the source folder is to be placed. Otherwise, you think that destination is the path name of the new folder to be created. If the destination folder already exists and the overwrite parameter is set to False, an error will be generated. The default overwrite parameter is True |
CreateFolder(foldername) |
Create a folder with the path name foldername. If the foldername already exists, an error will be generated |
DeleteFolder(folderspec,force) |
Delete all contents in one or more folders specified by folderspec (can contain via cards at the last part of the path) and in the folder. If the optional force parameter is set to true, the folder will be deleted even if the file contained in the folder has a read-only property. The default force parameter is False |
FolderExists(folderspec) |
Return True if the folder specified by folderspec exists, otherwise return False. folderspec parameter can contain the absolute or relative path of the folder, or just the folder name seen in the current folder |
GetAbsolutePathName(pathspec) |
Returns the path to the explicitly specified folder, which takes into account the path to the current folder. For example, if the current folder is "c:docssales" and pathspec is "jan", the returned character is "c:docssalesjan". Wildcards, ".." and "/" path operators are acceptable |
GetFolder(folderspec) |
Returns the Folder object corresponding to the folder specified by folderspec. folderspec can be a relative or absolute path to a folder |
GetParentFolderName(pathspec) |
Returns the previous folder of the pathspec file or folder. Do not check whether the folder exists |
GetSpecialfolder(folderspec) |
Returns the Folder object corresponding to a specific Windows folder. The allowed values of the parameter folderspec are WindowsFolder(0), SystemFolder(1) and TemporaryFolder(2) |
MoveFolder(source,destination) |
Move one or more folders specified by source to the folder specified by destination. Wildcards can be included in source, but not in destination. If source contains wildcards or destination is the path delimiter (''), then destination is considered to be the folder where the source folder is to be placed, otherwise it is considered to be the full path and name of a new folder. If the destination folder destination already exists, an error will occur |
Use of CopyFolder
Method name: CopyFolder(source, destination, overwrite)
Description: Recursively copy the folder from one location to another. For detailed instructions, please see Table 4.
Example:
' Create FileSystemObject object
Set objfso = createobject("")
' Copy all the contents under D:/test to c:/123
"D:/test","c:/123"
Note: If c:/123 does not exist, QTP will automatically create it
Use of CreateFolder and DeleteFolder
Method name: CreateFolder(foldername)/DeleteFolder(folderspec,force)
Description: Create/delete a folder with the path name foldername. For detailed instructions, please see Table 4.
Example:
' Create FileSystemObject object
Set objfso = createobject("")
‘Create a new folder folder in c:/. If the folder exists, an error message will appear.
("c:/new folder")
‘Delete the c:/new folder folder
("c:/new folder")
Note: DeleteFolder will delete the folder regardless of whether it contains content or not.
Use of FolderExists
Method name: FolderExist(folderspec)
Description: Returns True if the specified folder exists; otherwise, returns False. For detailed instructions, please see Table 4.
Example:
Function hanshu(strpath)
Dim objfso,objset
' Create FileSystemObject object
Set objfso = CreateObject("")
‘ Determine whether there is any in the specified path
If Not (strpath) Then
objset = (strpath)
else
objset = (strpath)
End If
hanshu = objset
End Function
hanshu("c:/new folder")
Use of GetAbsolutePathName
Method name: GetAbsolutePathName(pathspec)
Description: Returns a complete and well-meaning path from the specified path provided. For detailed instructions, please see Table 4.
Example:
Dim objfso
'Create FileSystemObject object
Set objfso = createobject("")
‘Return to the current directory, the following two statements return the same result
msgbox ((""))
msgbox (("C:"))
Use of GetFolder
Method name: GetFolder(folderspec)
Description: Returns the Folder object corresponding to a folder in the specified path. You can access the properties held by the Folder object based on the returned Folder object.
Example:
Dim objfso,objset
'Create FileSystemObject object
Set objfso = createobject("")
'Return the object of the Folder in C:/testing
Set objset = ("C:/testing")
' According to the returned Folder object, access its related properties
micDone ,"Folder object related properties","Date of folder creation: " & &"; The driver where the folder resides: " & & "; The name of the folder: " &
Note: About the properties of the Folder object, we will introduce them in detail below.
Use of GetParentFolderName
Method name: GetParentFolderName(pathspec)
Description: Returns a string containing the parent folder of the last file or folder in the specified path.
Example:
Dim objfso
'Create FileSystemObject object
Set objfso = createobject("")
'Use GetParentFolderName method to return the previous folder
msgbox (("C:/WINDOWS/addins"))
Use of GetSpecialFolder
Method name: GetSpecialFolder(folderspec)
Description: Returns the specified special folder. For detailed instructions, please see Table 4.
Example:
Dim fso,tempName
Set fso = CreateObject("")
'Argument 2 in GetSpecialFolder() returns a temporary folder named Temp
Set tempName = (2)
msgbox tempName
Use of MoveFolder
Method name: MoveFolder(source, destination)
Description: Move one or more folders from one location to another. For detailed instructions, please see Table 4.
Example:
Dim sourcepath,destination
sourcepath = "C:/testing"
destination = "C:/123"
'Call the MoveFolders method
call MoveFolders(sourcepath,destination)
Sub MoveFolders(sourcepath,destination)
Dim fso
'Create FileSystemObject object
Set fso = CreateObject("")
'Use the MoveFolder method to move the contents of the testing folder to the 123 folder
sourcepath,destination
End Sub
Note: If the script already exists before running, an error will occur when running; the MoveFolder method cannot be used on different disks.
The Folder method mentioned above is based on the FileSystemObject object. Now let’s take a look at the methods based on the Folder object.
Methods provided by Folder objects
The Folder object provides a set of methods that can be used to copy, delete, and move the current folder. These methods run the same way as the CopyFolder, DeleFolder, and MoveFolder methods of the FileSystemObject object, but these methods do not require the source parameter because the source file is the folder.
Note: CopyFolder, DeleFolder and other methods are based on FileSystemObject object; while the following Copy, Delete and other methods are based on Folder objects under FileSystemObject object, and the functions they implement are similar.
Table 5 Methods and descriptions of Folder objects |
|
method |
illustrate |
Copy(destination,overwrite) |
Copy this folder and all contents to the folder specified by destination. If the end of destination is the path separator (''), then destination is considered to be a folder where the copy folder is placed. Otherwise, it is considered that destination is the path and name of the new folder to be created. If the target folder already exists and the overwrite parameter is set to False, an error will be generated. The default overwrite parameter is True |
Delete(force) |
Delete the folder and all contents inside。 If the optional force parameter is set to True, the folder will be deleted even if it is set to read-only or contains read-only files. Default force yes False |
Move(destination) |
Move the folder and all contents in it to the folder specified by destination. If the end of destination is the path separator (''), then destination is considered to be a folder where the moving folder is placed. Otherwise, destination is considered to be the path and name of a new folder. If the target folder already exists, an error occurs |
CreateTextFile(filename,overwrite,unicode) |
Create a new file in the folder with the specified file name and return a corresponding TextStream object. If the optional overwrite parameter is set to True, any existing file of the same name will be overwritten. The default overwrite parameter is False. If the optional unicode parameter is set to True, the content of the file will be stored as unicode text. The default unicode is False |
Use of Copy
Method name: Copy(destination, overwrite)
Description: Copy all the contents of the folder into the destination folder. For detailed description, please refer to Table 5
Example:
Dim sourcepath
sourcepath = "C:/testing"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
'Copy everything in the test into the 123 folder
("d:/123")
End Sub
Note: If the target folder does not exist, the script will be created automatically when it is running.
Use of Delete
Method name: Delete(force)
Description: Delete the folder and all contents inside. For detailed description, please refer to Table 5
Example:
Dim sourcepath
sourcepath = "C:/testing"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
'Delete all contents in the testingw folder and folders
(True)
End Sub
Note: If the folder attribute is read-only and the parameter of Delete is False, the script will prompt "no permissions" when it is running; when the folder does not exist, the message will prompt "path not found".
Use of Move
Method name: Move(destination)
Description: Move the folder and all contents in it to the folder specified in destination. For detailed description, please refer to Table 5
Example:
Dim sourcepath
sourcepath = "C:/testing"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
'Use Move() to move the testing folder and all the contents in it to the target folder 123
("C:/123")
End Sub
Note: If the target folder 123 already exists, the script prompts "the file already exists" when running; if the target folder 123 is in D:/, the script runs to prompt "no permissions"
Use of CreateTextFile
Method name: CreateTextFile(filename, overwrite, unicode)
Description: Creates a specified file and returns a TextStream object that can be used to read or write the created file. For detailed description, please refer to Table 5.
Example:
Dim sourcepath
sourcepath = "C:/testing"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
'Under the testing folder, use CreateTextFile() to create a file
"",true
End Sub
Note: The file type created by CreateTextFile() is determined based on the provided extension, such as it can be written as, etc.; the FileSystemObject object can also call CreateTextFile(), and we can rewrite the above code as:
“C:/testing/”,true
Properties provided by the Folder object:
Table 6 Folder object properties and description |
|
property |
illustrate |
Attributes |
Return the properties of the folder。 It can be one or a combination of the following values: Normal(0), ReadOnly(1), Hidden(2), System(4), Volume(name)(8), Directory(folder)(16), Archive(32), Alias(64) and Compressed(128). For example, a hidden read-only file, the value of Attributes is 3 |
DateCreated |
Returns the date and time of creation of this folder |
DateLastAccessed |
Returns the date and time of the last access to the folder |
DateLastModified |
Returns the date and time when the folder was last modified |
Drive |
Returns the drive letters of the drive where the folder resides |
Files |
Returns the Files collection contained in the Folder object, indicating all files in the folder |
IsRootFolder |
Return a boolean value to indicate whether the folder is the root folder of the current drive |
Name |
Set or return the name of the folder |
ParentFolder |
Return the Folder object corresponding to the parent folder of this folder |
Path |
Return the absolute path to the folder, using the corresponding long file name |
ShortName |
Returns the folder name in the DOS style form 8.3 |
ShortPath |
Returns the absolute path to the folder in the form of DOS style 8.3 |
Size |
Returns the size of all files and subfolders contained in the folder |
SubFolers |
Returns the Folders collection corresponding to all subfolders contained in this folder, including hidden folders and system folders |
Type |
If possible, return a folder's description string (for example, "Recycle Bin") |
As mentioned above, we can use the following script to access the Folder object
Dim objfso,objset
'Create FileSystemObject object
Set objfso = createobject("")
'Return the object of the Folder in C:/testing
Set objset = ("C:/testing")
Note: Through the Folder object, we can access the methods and properties provided by it.
Use of Drive, DateCreated, Name attributes
Example:
Dim sourcepath
sourcepath = "C:/testing"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
'Access to Folder attributes through Folder object
micDone , "Test Folder Properties", "The disk where the folder is located is: " & & " The date the folder was created: " & & " The name of the folder is: " &
End Sub
Use of SubFolers attributes
Example:
Dim sourcepath
sourcepath = "C:/Program Files/Common Files"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objset,objFolders,FolderName,i
i = 0
Set fso = CreateObject("")
'Use the GetFolder method to return the Folder object
Set objset = (sourcepath)
The SubFolders property will return the Folder collection corresponding to all subfolders
Set objFolders =
'Travel over the Folder collection and count how many folders there are, and the names of the related folders
For Each objFolder in objFolders
i = i +1
'vbcr is a newline
FolderName = FolderName + + vbcr
Next
msgbox ("Total" & i &" folders, the name of the folder is: " & FolderName)
End Sub
Use of Files attributes
Example:
Dim objFso,objGetFolder,intCount,strFileName
intCount = 0
'Create FileSystemObject object
Set objFso= CreateObject("")
'Use GetFolder() to get folder object
Set objGetFolder = ("C:/test")
'Travel over the Files collection and display all file names in the folder
For Each strFile in
intCount = intCount + 1
strFileName =strFileName & "Thread" & intCount & "Folders are named:" & & vbcr
Next
msgbox strFileName
3. File-related methods and attributes
How to use FileSystemObject object to manipulate files:
Table 7 Methods and descriptions related to documents |
|
method |
illustrate |
CopyFile(source,destination,overwrite) |
Copy one or more files specified by source (can contain wildcards) to the specified destination folder destination. If source contains wildcards or destination is the path delimiter (''), then destination is considered a folder. Otherwise, destination is considered to be the full path and name of a new file. If the target folder already exists and the overwrite parameter is set to False, an error will be generated. The default overwrite parameter is True |
CreateTextFile(filename,overwrite,unicode) |
Create a new text file on disk with the specified file name filename and return the corresponding TextStream object. If the optional overwrite parameter is set to True, it will overwrite the existing file of the same name under the same path. The default overwrite parameter is False. If the optional unicode parameter is set to True, the content of the file will be stored as Unicode text, and the default unicode parameter is False |
DeleFile(filespec,force) |
Delete one or more files specified by filespec (can contain wildcards at the last part of the path). If the optional force parameter is set to true, then the files with read-only attributes are also deleted. The default force parameter is False |
FileExists(filespec) |
Return True if the file specified by filespec exists, otherwise return False. The filespec parameter can contain the absolute or relative path of the file, or the file name in the current folder. |
GetBaseName(filespec) |
Returns the name of the file specified by filespec, that is, the extension of the file that contains the file path but removes the file |
GetExtensionName(filespec) |
Returns the file extension specified by filespec |
GetFile(filespec) |
Returns the File object corresponding to the file specified by filespec. You can specify the relative or absolute path to the file |
GetFileName(pathspec) |
Returns the pathspec file path or file name, if there is no file name, the last folder name is returned. Do not check whether the file or folder exists |
GetTempName() |
Returns a randomly generated file name, used for the temporary file or folder required to complete the operation |
MoveFile(source,destination) |
Move one or more source files specified by source to the destination folder specified by destination. Wildcards can be included in source, but destination cannot. If source contains a path separator ('') by a card or destination is the end of it, then destination is considered a folder. Otherwise, destination is considered to be the complete path and name of a new folder. If the destination folder already exists, an error will occur |
OpenTextFile(filename,iomode,create,format) |
Create a file named filename, or open an existing file named filename, and return a TextStream object related to it. The filename parameter can contain absolute or relative paths. The iomode parameter specifies the required access type. The allowed values are ForReading(1) (default), ForWriting(2), and ForAppending(8). When writing or appending to a non-existent file, if the create parameter is set to true, a new file will be created. The default create parameter is False. format parameter indicates the data format to read or write to the file. The allowed values are: TristatetFalse(0) (default), open in ASCII format; TristatetTrue(-1), open in Unicode format; TristateDefault(-2), open in system default format |
Use of CopyFile and MoveFile
Method name: CopyFile(source, destination, overwrite)
Description: Copy one or more files from one location to another. For detailed description, please refer to Table 7
Method name: MoveFile(source, destination)
Description: Move one or more source files specified by source to the destination folder specified by destination.
Example:
Dim sourcepath,targetpath
sourcepath = "C:/testing/*.txt"
targetpath = "C:/123/"
Call FolderAttributes(sourcepath,targetpath)
Sub FolderAttributes(sourcepath,targetpath)
Dim fso
Set fso = CreateObject("")
'Copy all files with extension name .txt in the testing folder to folder 123
sourcepath,targetpath
sourcepath,targetpath
End Sub
Note: If the C:/123 folder does not exist, the script prompts "The path does not exist" when running.
Use of CreateTextFile and DeleteFile
Method name: CreateTextFile(filename, overwrite, unicode)
Description: Creates a specified file and returns a TextStream object that can be used to read or write the created file.
Method name: DeleFile(filespec,force)
Description: Delete the specified file. For detailed description, please refer to Table 7.
Example:
Dim sourcepath
sourcepath = "C:/testing/ "
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso
Set fso = CreateObject("")
'Under the testing folder, use CreateTextFile() to create a file
sourcepath,true
'Delete all files with the extension .txt under the testing folder
sourcepath,true
End Sub
Note: If the deleted file is a read-only property and the parameter of DeleteFile() is false, the script runs and uses FileExists without permissions.
Method name: FileExists(filespec)
Description: Determine whether the specified file exists. This method will return the Bool value. For detailed description, see Table 7.
Example:
Dim sourcepath
sourcepath = "C:/testing/"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso
Set fso = CreateObject("")
'Judge whether C:/testing/ exists, and if it exists, return "true"; otherwise return "false"
If (sourcepath) Then
msgbox "true"
else
msgbox "false"
End If
End Sub
Use of GetBaseName, GetFileName and GetExtensionName
Method name: GetBaseName(filespec)
Description: Returns a string, file (without extension), or folder in the path description provided.
Method name: GetExtensionName(filespec)
Description: Returns a string containing the extension of the last component of the path.
Method name: GetFileName(pathspec)
Description: Returns the last file or folder of the specified path (not the specified drive path part).
Example:
Dim sourcepath
sourcepath = "C:/testing/"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso
Set fso = CreateObject("")
'Return to file name test, extension txt, file name + extension
Msgbox ((sourcepath))
Msgbox (fso. GetExtensionName(sourcepath))
Msgbox ((sourcepath))
End Sub
Use of GetFile
Method name: GetFile(filespec)
Description: Returns the File object corresponding to a file in the specified path, and then you can access the File properties.
Example:
Dim sourcepath
sourcepath = "C:/testing/"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objFile
Set fso = CreateObject("")
'Call GetFile() to return the File object and access the properties under it through the File object.
set objFile = (sourcepath)
micDone,"Access file properties","The drive letter where the file is located is: " & & "
End Sub
Note: About the properties of File objects, we will introduce them in detail below.
Use of GetTempName
Method name: GetTempName()
Description: Returns the name of a randomly generated temporary file or folder to perform operations requiring temporary files or folders.
Example:
Dim fso, tempfile
'Create FileSystemObject object
Set fso = CreateObject("")
'Call the CreateTempFile function and assign the object to the tempfile
Set tempfile = CreateTempFile
'Write characters in temporary files
"Hello the world"
'Close the object
Function CreateTempFile
Dim tfolder, tname, tfile
Const TemporaryFolder = 2
'Argument 2 in GetSpecialFolder() returns a temporary folder named Temp
Set tfolder = (TemporaryFolder)
'Create a temporary file name randomly
tname =
'Below the Temp temporary folder, create a temporary file
Set tfile = (tname)
'Assign the result to the function
Set CreateTempFile = tfile
End Function
Note: The GetTempName method does not create a file, and this method only provides temporary file names. The results in the example are saved by default in C:/Documents and Settings/Administrator/Local Settings/Temp
Use of OpenTextFile
Method name: (filename,iomode,create,format)
Description: Opens the specified file and returns a TextStream object that can be read, written to, or appended to the file. See Table 7 for detailed descriptions.
Example:
Dim spec
spec = "C:/"
'The three parameters are: open the file in read-only mode, open the file in write-only mode, open the file and write at the end of the file
Const intForReading = 1,intForWriting = 2,intForAppending = 8
'Call OpenTextFileTest()
Call OpenTextFileTest(spec,intForAppending)
Sub OpenTextFileTest(sepc,intForAppending)
Dim fso,objTStream
'Create FileSystemObject object
Set fso = CreateObject("")
'Argument true means: If the file does not exist, create the file. Finally OpenTextFile() will return the TextStream object
Set objTStream = (sepc,intForAppending,true)
'Use TextStream object to write strings to file
"hello word!"
'Release the TextStream object
End Sub
Properties provided by File object
Table 8 Properties and descriptions of File object |
|
property |
illustrate |
Attributes |
Returns the properties of the file. It can be one or a combination of the following values: Normal(0), ReadOnly(1), Hidden(2), System(4), Volume(name)(9), Directory(folder)(16), Archive(32), Alias(64) and Compressed(128) |
DateCreated |
Returns the date and time of creation of this folder |
DateLastAccessed |
Returns the date and time of the last access to the file |
DateLastModified |
Returns the date and time when the file was last modified |
Drive |
Return the Drive object of the drive where the file resides |
Name |
Set or return the file name |
ParentFolder |
Returns the Folder object of the parent folder of the file |
Path |
Returns the absolute path to the file, and can use a long file name |
ShortName |
Returns the file name in DOS style form 8.3 |
ShortPath |
Returns the file absolute path in DOS style 8.3 form |
Size |
Returns the size of the file (bytes) |
Type |
If possible, return a description string of file type (for example: "Text Document" means .txt file) |
We mentioned in the previous File object method that you can use GetFile() of the FileSystemObject object to access File object properties.
An example of accessing File object properties is as follows:
Dim sourcepath
sourcepath = "C:/testing/"
Call FolderAttributes(sourcepath)
Sub FolderAttributes(sourcepath)
Dim fso,objFile
Set fso = CreateObject("")
'Call GetFile() to return the File object and access the properties under it through the File object.
set objFile = (sourcepath)
micDone,"Access file properties", "The drive letter where the file resides is: " & & " The file name is: " &
End Sub
Note: The usage method of File object attributes is the same as the usage method of Folder object attributes introduced earlier, so they will not be listed here one by one.
TextStream Object Overview
The TextStream object is an object used to access text files. It is a separate affiliate object of FileSystemObject. However, when using the TextStream object, we still need to use the FileSystemObject object or its affiliate object to create a TextStream object and access the contents of the disk file. You can obtain the object handle of the TextStream through CreateTextFile() and OpenTextFile() of the FileSystemObject object.
Let’s take a look at the methods and properties of TextStream objects in detail.
1. Methods of TextStream object
Table 9 Methods and descriptions of TextStream objects |
|
method |
illustrate |
Close() |
Close an open file |
Read(numchars) |
Read numchars characters from the file |
ReadAll() |
Read the entire file as a single string |
ReadLine() |
Read a line from the file as a string (until the carriage return and line break) |
Skip(numchars) |
Ignore numchars characters when reading from a file |
SkipLine() |
Ignore the next line when reading from a file |
Write(string) |
Write string to file |
WriteLine(string) |
Write strings to files strings (optional) and line breaks |
WriteBlankLines(n) |
Write n newline characters to the file |
Use of Close, Write, WriteLine and WriteBlankLines
Method name: Close()
Description: Close the file being opened
Method name: WriteLine(string)
Description: Write string (optional) and line breaks to the file.
Example:
Dim strPath,strText strPath = "C:/" strText = "This is Test !" & vbCrLf & “hello word !” 'Calling functions Call CreateFile(strPath,strText) Sub CreateFile(strPath,strText) Dim objFso,objStream 'createFileSystemObjectObject Set objFso = CreateObject("") 'useFileSystemObjectObject的CreateTextFile(),Come back to oneTextStreamObject句柄 Set objStream = (strPath,True) 'ThreeWriteThe meanings are:Write characters in text、Write characters with newline characters、Write3Line breaks (strText) ‘(strText) ‘objStream. WriteBlankLines 3 'closureTextStreamObject End Sub
Use of Read, ReadAll and ReadLine
Method name: Read(numchars)
Description: Read the specified number of characters from the TextStream file and return the result string.
Method name: ReadAll()
Description: Read all TextStream files and return the result string.
Method name: ReadLine()
Description: Read a full line of characters from the TextStream file (until the next line, but not the next line), and return the result string.
Example:
Sub CreateFile(strPath,strText) Dim objFso,objStream 'createFileSystemObjectObject Set objFso = CreateObject("") 'useFileSystemObjectObject的CreateTextFile(),Come back to oneTextStreamObject句柄 Set objStream = (strPath,True) 'Write characters (strText) Set objStream = (strPath,1,true) msgbox () 'msgbox () ' msgbox ((Len(strText))) 'closureTextStreamObject End Sub
Use of Skip and SkipLine
Method name: Skip(numchars)
Description: Skip the specified number of characters when reading a TextStream file
Method name: SkipLine()
Description: When reading a TextStream file, skip the next line.
Example:
Dim strPath,strText strPath = "C:/" 'Calling functions Call CreateFile(strPath) Sub CreateFile(strPath) Dim objFso,objStream 'createFileSystemObjectObject Set objFso = CreateObject("") 'useFileSystemObjectObject的CreateTextFile(),Come back to oneTextStreamObject句柄 Set objStream = (strPath,True) 'Write characters in text "This is Test !" & vbCrLf & "hello word !" 'Open a file read-only Set objStream = (strPath,1,true) 'Skip when reading a file5Characters;Or skip the current line,Read the next line (5) ' 'Read text content msgbox 'closureTextStreamObject End Sub
Note: The difference between the two is: Skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-skip-ski
2. Properties of TextStream object
The properties of TextStream provide information about the current location of the file pointer in the file, as shown in Table 9. Note that all properties are read-only.
Table 10 The properties and description of the TextStream object |
|
property |
illustrate |
AtEndOfLine |
If the file position pointer is at the end of a line in the file, it returns True |
AtEndOfStream |
Return True if the file location pointer is at the end of the file |
Column |
Return the column number of the current character in the file starting from 1 |
Line |
Starting from 1, return the line number of the current line in the file” |
The AtEndOfLine and AtEndOfStream properties are only available for files that are opened with the iomode parameter ForReading, otherwise an error will occur.
Use of AtEndOfLine and AtEndOfStream
Example:
Dim strPath,strText strPath = "C:/" 'Calling functions Call CreateFile(strPath) Sub CreateFile(strPath) Dim objFso,objStream,str 'createFileSystemObjectObject Set objFso = CreateObject("") 'Open a file read-only,如果文件不存在则create它 Set objStream = (strPath,1,true) 'If the current pointer is not at the end of the line,Read the text content Do While <> true ‘Do While <> true str = str + (1) Loop msgbox str 'closureTextStreamObject End Sub
Note: The difference between the two is: AtEndOfLine - read to the end of the current text line; AtEndOfStream - read to the end of the entire text
Column and Line use
Example:
Sub TestTextStream(strPath) Dim objFso,objTStream,str Set objFso = CreateObject("") 'Open a file read-only Set objTStream = (strPath,1) 'If the current pointer is not at the end of the entire document,Read all contents of text Do While <> true str = str + "Common" & & "Line data, the last column number where the cursor is located is:" & & vbCrLf Loop 'Print information print str End Sub
FileSystemObject instance code
Create a file
set fso = ("") set f = ("C:\", true) 'The second parameter indicates whether the target file is overwritten when it exists. ("Write content") ("Write content and wrap line") (3) 'Write three blank lines(It is equivalent to pressing three times to enter the text editor) () set f = nothing set fso = nothing
Open and read the file
set fso = ("") set f = ("C:\", 1, false) 'The second parameter 1 It means read-only,The third parameter indicates whether the target file does not exist. (3) 'Move the current position backward by three characters () 'Move the current position to the first character on the next line,Notice:No parameters (3) 'Read three characters backward from the current position,并Move the current position backward by three characters () 'Read backward from the current position until a newline is encountered(No newline characters are read),并Move the current position to the first character on the next line,Notice:No parameters () 'Read backward from the current position,Until the end of the file,and move the current location to the end of the file if then ("The end of a line!") end if if then ("The end of the file!") end if () set f = nothing set fso = nothing
Open and write a file
set fso = ("") set f = ("C:\", 2, false) 'The second parameter 2 Indicates rewrite,in the case of 8 Indicates additional ("Write content") ("Write content and wrap line") (3) 'Write three blank lines(It is equivalent to pressing three times to enter the text editor) () set f = nothing set fso = nothing
Determine whether the file exists
set fso = ("") if ("C:\") then ("The target file exists") else ("The target file does not exist") end if set fso = nothing
Move files
set fso = ("")
call ("C:\", "D:\") 'The file name parts of the two parameters can be different
set fso = nothing
Copy the file
set fso = ("")
call ("C:\", "D:\") 'The file name parts of the two parameters can be different
set fso = nothing
Delete files
set fso = ("")
("C:\")
set fso = nothing
Create a folder
set fso = ("")
("C:\test") 'The parent folder of the target folder must exist
set fso = nothing
Determine whether the folder exists
set fso = ("")
if ("C:\Windows") then
("The target folder exists")
else
("The target folder does not exist")
end if
set fso = nothing
Delete folder
set fso = ("")
("C:\test") 'Folder does not have to be empty
set fso = nothing
Detect whether the drive C drive exists
Set fso = ("")
("c:")
Get the drive name of the file path
Set fso=("")
p=(("aqa33"))
("Drive name is:" & p)
set fs=nothing
Get the name of the parent folder of a specified path
Set fso=("")
p=((""))
("The parent folder name is:" & p)
set fs=nothing
Get the file extension of the last component in the specified path
Set fs=("")
((("")))
set fs=nothing
Get the file name of the last component in the specified path
Set fs=("")
((("")))
set fs=nothing
Returns the basic name of the file or folder in the specified path.
Set fso=("")
(("c:\windows\cursors\"))
("<br />")
(("c:\windows\cursors\"))
("<br />")
(("c:\windows\"))
set fso=nothing
Okay, that's all for this article, basically the content is almost done. I hope everyone will support me in the future.