Using the FSO (File System Object)

 

The File System Object (FSO) object model provides an object-based tool for working with folders and files. Using "object.method" syntax, it exposes a comprehensive set of properties and methods to perform file system operations such as creating, moving, deleting, and providing information about folders and files. The FSO also provides methods for reading and writing sequential text files, however it does NOT have methods for processing binary or random files.

 

The FSO is (or should be) used primarily with VBScript. VBScript is a scripting language used with ASP for web development; VBScript is also used for Windows scripting. (Windows scripting files, which have a ".vbs" extension, can be thought of as a modern-day replacement for the MS-DOS "BAT" files used in the days of yore). VBScript is a pared-down version of  Visual Basic, and as such does not have all of the functionality of  "VB  proper".  One of the things missing in VBScript is the set of native VB file processing statements and functions discussed in the last several topics – so in VBScript, the FSO must be used to manipulate files and folders. However, VB proper can make use of the FSO in addition to its native file processing commands.

 

There are some trade-offs in using the FSO with Visual Basic. On the one hand, the FSO can make certain tasks easier to program with smoother and less arcane syntax than the native VB statements. On the other hand, using the FSO requires adding an additional dependancy to your project, it is slower, it does not support the reading or writing of random and binary files, and it can be disabled by system administrators concerned about security.

 

To use the FSO with your VB project, you must add a reference to "Microsoft Scripting Runtime" (which is the system file "SCRRUN.DLL"). To do this, from the VB IDE, first go to the Project menu, and select References, as shown below:

 

 

From the References dialog box, check Microsoft Scripting Runtime, as shown below, and click OK.

 

 

Once you have done the above, you can use the FSO in your VB project. In your code, you must declare an object variable for the FSO and instantiate it. The most concise way of doing this is use the "New" keyword in your declaration, as shown below. (Note: The "Scripting." qualifier is optional here.)

 

      Dim objFSO As New Scripting.FileSystemObject

 

An alternative way of doing this is to declare the FSO variable without the "New" keyword and instantiate it later with the "Set" statement, as shown below.  (Note: Again, the "Scripting." qualifier is optional.)

 

      Dim objFSO As Scripting.FileSystemObject

      ...

      Set objFSO = New Scripting.FileSystemObject

 

You can also use "late binding" by declaring the FSO variable as a generic "object" and then using the "CreateObject" method to instantiate it later, as shown below. This is the slowest method, but it is the way it must be done in VBScript. The "Scripting." qualifier is required here.

 

      Dim objFSO As Object

      ...

      Set objFSO = CreateObject("Scripting.FileSystemObject")

 

The tables below show the various objects, properties, and methods available with the FSO.

 

FSO Objects

 

Object

Description

FileSystemObject

The FSO itself, highest level of the FSO object model. Allows the programmer to interact with Files, Folders and Drives. The programmer can use the FSO objects to create directories, move files, determine whether or not a Drive exists, etc.

Drive

The Drive object is used to examine information on disk, CD-ROM, RAM disk, and network drives; the Drives collection provides a list of physical and logical drives on the system.

File object

The File object is used to examine and manipulate files; the Files collection provides a list of files in a folder.

Folder object

The Folder object  is used to examine and manipulate folders; the Folders collection provides a list of subfolders in a folder.

TextStream object

Used to read and write text files.

 

Property of the FileSystemObject

 

Property

Description

Drives

Returns a Drives collection, which is a list of physical and logical drives on the system.

 

Methods of the FileSystemObject

 

Method

Description

BuildPath

Appends file path information to an existing file path.

CopyFile

Copies files from one location to another.

CopyFolder

Copies folders and their contents from one location to another.

CreateFolder

Creates a folder.

CreateTextFile

Creates a text file and returns a TextStream object.

DeleteFile

Deletes a file.

DeleteFolder

Deletes a folder and all of its contents.

DriveExists

Determines if a drive exists.

FileExists

Determines if a file exists.

FolderExists

Determines if a folder exists.

GetAbsolutePathName

Returns the full path to a file or folder.

GetBaseName

Returns the base name of a file or folder.

GetDrive

Returns a drive object.

GetDriveName

Returns a drive name.

GetExtensionName

Returns a file extension from a path.

GetFile

Returns a file object.

GetFileName

Returns a filename from a path.

GetFolder

Returns a folder object.

GetParentFolderName

Returns the parent folder name from a path.

GetSpecialFolder

Returns an object pointer to a special folder.

GetTempName

Returns a temporary (randomly generated) file or folder name that can be used with CreateTextFile.

MoveFile

Moves files from one location to another.

MoveFolder

Moves folders and their contents from one location to another.

OpenTextFile

Opens an existing text file and returns a TextStream object.

 

 

Properties of the Drive Object

 

Property

Description

AvailableSpace

The amount of available Drive space in bytes.

DriveLetter

A string containing the letter of the Drive without a colon (e.g., "C").

DriveType

An integer value indicating the Drive type. Possible values are 0 (Unknown), 1 (Removable), 2 (Fixed), 3 (Remote), 4 (CD-ROM) and 5 (RAM Disk).

FileSystem

A string indicating the file system Drive description ("FAT", "FAT32", "NTFS", etc.).

FreeSpace

Same as AvailableSpace .

IsReady

A Boolean indicating whether or not a Drive is ready for use.

Path

A string containing the Drive's path (e.g., "C:\")

RootFolder

A Folder object containing the root folder of Drive.

SerialNumber

A long value containing the Drive serial number.

ShareName

With network drives, returns a string containing the network share name.

TotalSize

The total Drive size in bytes.

VolumeName

A string value containing the Drive volume name.

 

Properties of the Folder Object

 

Property

Description

Attributes

An integer value indicating Folder's attributes. Possible values are 0 (Normal), 1 (ReadOnly), 3 (Hidden), 4 (System), 8 (Volume), 16 (Directory), 32 (Archive), 64 (Alias), and 128 (Compressed).

DateCreated

The date the folder was created.

DateLastAccessed

The date the folder was last accessed.

DateLastModified

The date the folder was last modified.

Drive

The Drive where the folder is located.

IsRootFolder

A Boolean indicating whether or not a Folder is the root folder.

Name

A string containing the Folder's name.

ParentFolder

A string containing the Folder's parent folder name.

Path

A string containing the Folder's path.

ShortName

A string containing the Folder's name expressed as an MS-DOS compliant ("8.3") short name.

ShortPath

A string containing the Folder's path expressed as a short (MS-DOS compliant) path.

Size

The total size in bytes of all subfolders and files.

Type

A string containing the Folder type (e.g., "File Folder").

 

Methods of the Folder Object

 

Method

Description

Delete

Deletes the Folder. Same as DeleteFolder of FileSystemObject.

Move

Moves the Folder. Same as MoveFolder of FileSystemObject.

Copy

Copies the Folder. Same as CopyFolder of FileSystemObject.

 

Properties of the File Object

 

Property

Description

Attributes

An integer value indicating File's attributes. Possible values are 0 (Normal), 1 (ReadOnly), 3 (Hidden), 4 (System), 8 (Volume), 16 (Directory), 32 (Archive), 64 (Alias), and 128 (Compressed).

DateCreated

The date the file was created.

DateLastAccessed

The date the file was last accessed.

DateLastModified

The date the file was last modified.

Drive

The Drive where the file is located.

Name

A string containing the File's name.

ParentFolder

The Folder object of the file's parent folder.

Path

A string containing the File's path.

ShortName

A string containing the File's name expressed as a short (MS-DOS compliant "8.3") name.

ShortPath

A string containing the File's path expressed as a short (MS-DOS compliant) path.

Size

The total size in bytes of the file.

Type

A string containing the File type (e.g., "Microsoft Word Document").

 

Methods of the File Object

 

Method

Description

Delete

Deletes the File. Same as DeleteFile of FileSystemObject.

Move

Moves the File. Same as MoveFile of FileSystemObject.

Copy

Copies the File. Same as CopyFile of FileSystemObject.

CreateTextFile

Returns a TextStream object that can be used to work with the newly created file.

OpenAsTextStream

Opens an existing text file and returns a TextStream object.

 

Properties of the TextStream Object

 

Property

Description

AtEndOfLine

A Boolean indicating whether or not the file pointer is at the end of a line in the text file (used when reading character by character).

AtEndOfStream

A Boolean indicating whether or not the file pointer is at the end of file (used when reading line by line).

Column

The column number of the current character position in a TextStream file.

Line

The current line number in a TextStream file.

 

Methods of the TextStream Object

 

Property

Description

Close

Closes an open TextStream file.

Read

Reads a specified number of characters from a TextStream file and returns the resulting string.

ReadAll

Reads an entire TextStream file and returns the resulting string.

ReadLine

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

Skip

Skips a specified number of characters when reading a TextStream file.

SkipLine

Skips the next line when reading a TextStream file.

Write

Writes a specified string to a TextStream file.

WriteLine

Writes a specified string and newline character to a TextStream file.

WriteBlankLines

Writes a specified number of newline characters to a TextStream file.

 

 

Sample Program 1

 

The first sample program is equivalent of the sample program presented in the previous topic on File System Commands and Functions. The previous topic used the native VB commands, this topic will use the FSO.

 

For convenience, the "task at hand" is repeated below:

 

As a vehicle to demonstrate commonly used file system commands and functions, the tasks in a student exercise to practice MS-DOS commands has become the work to be done by the sample program.

 

Let us take a look at the original student exercise. The students were given a floppy disk containing the following files, all in the root directory:

 

 

The students were instructed to make six directories on their disk and move the indicated files to their proper directory as shown below. When done with this step, there should be NO files in the root directory.

 

Create a directory called:

For files with these extensions:

SYSTEM

.SYS

COMMAND

.COM

EXECUTE

.EXE

INITIAL

.INI

TEXT

.TXT

WRITE

.WRI

 

To do this step they would have to do the following:

 

First, make the directories:

 

      MD SYSTEM

      MD COMMAND

      MD EXECUTE

      MD INITIAL

      MD TEXT

      MD WRITE

 

Next, they would have to move the appropriate set of files from the root to the proper directory. This could be accomplished with either a set of MOVE commands or a set of COPY and DELETE combinations:

 

      MOVE A:\*.SYS A:\SYSTEM

      MOVE A:\*.COM A:\COMMAND

      MOVE A:\*.EXE A:\EXECUTE

      MOVE A:\*.INI A:\INITIAL

      MOVE A:\*.TXT A:\TEXT

      MOVE A:\*.WRI A:\WRITE

 

               - or -

 

      COPY A:\*.SYS A:\SYSTEM

      DEL A:\*.SYS

      COPY A:\*.COM A:\COMMAND

      DEL A:\*.COM

      COPY A:\*.EXE A:\EXECUTE

      DEL A:\*.EXE

      COPY A:\*.INI A:\INITIAL

      DEL A:\*.INI

      COPY A:\*.TXT A:\TEXT

      DEL A:\*.TXT

      COPY A:\*.WRI A:\WRITE

      DEL A:\*.WRI

 

For the last step, they were instructed as follows:

 

Below the SYSTEM subdirectory, create a directory called EXE_INI.  Place copies of the .EXE and .INI files there. Below the INITIAL subdirectory, create a directory call TXT_WRI.  Place copies of the .TXT and .WRI files there.

 

To do this, they would have to issue the following commands:

 

      MD A:\SYSTEM\EXE_INI

      COPY A:\EXECUTE\*.EXE A:\SYSTEM\EXE_INI

      COPY A:\INITIAL\*.INI A:\SYSTEM\EXE_INI

 

      MD A:\INITIAL\TXT_WRI

      COPY A:\TEXT\*.TXT A:\INITIAL\TXT_WRI

      COPY A:\WRITE\*.INI A:\ INITIAL\TXT_WRI

 

The student would then turn their disk into the instructor, who would check to make sure that all the proper directories were created and that the files were in the right place.

 

As a follow-up exercise, students were given the disks back and asked to restore the disk back to its original state – i.e., all files back in the root with no subdirectories.

 

To do this, they would have to move the *.SYS, *.COM, *.EXE, *.INI, *.TXT, and *.WRI files from their respective top-level directories back to the root. This could be accomplished with the following MS-DOS (Windows command-line) commands:

 

      MOVE A:\SYSTEM\*.* A:\

      MOVE A:\COMMAND\*.* A:\

      MOVE A:\EXECUTE\*.* A:\

      MOVE A:\INITIAL\*.* A:\

      MOVE A:\TEXT\*.* A:\

      MOVE A:\WRITE\*.* A:\

 

At this point, the COMMAND, EXECUTE, TEXT, and WRITE subdirectories are cleared out, so they could be removed with the "remove directory" command (RMDIR or RD) as follows:

 

      RD A:\COMMAND

      RD A:\EXECUTE

      RD A:\TEXT

      RD A:\WRITE

 

However, since second-level directories were created below both the SYSTEM and the INITIAL directories, those directories must be cleared out before they can be removed (the RD command will only work if the directory to be removed is empty).

 

Therefore, the files in the EXE_INI directory below the SYSTEM directory must be deleted:

 

      DEL A:\SYSTEM\EXE_INI\*.*

 

Then the EXE_INI directory can be removed:

 

      RD A:\SYSTEM\EXE_INI

 

Then the top-level SYSTEM directory can be removed:

 

      RD A:\SYSTEM

 

A similar set of commands is necessary to clear the INITIAL directory:

 

      DEL A:\INITIAL\TXT_WRI\*.*

      RD A:\INITIAL\TXT_WRI

      RD A:\INITIAL

 

At this point, the exercise would be complete and the disk could be turned back into the instructor.

 

To do the sample project that implements these actions, you need a "clean" (empty) floppy disk. The sample files shown above (the .SYS, .INI, etc.) should then be copied to that disk. The project download below, when unzipped, contains a folder called "FileSysDemoFiles", from where the files can be copied. (As an alternative, you can simply make empty files using Notepad and save them with those names, and then copy them to a floppy. For the purpose of this exercise, the content of these files do not matter; for example, the "exe" and "com" files need not be valid executables.)

 

The sample project is a modified "Try It" program. The "Clear" button was changed to "Reset" (the caption was changed "Reset" and the name was changed to "cmdReset").

 

 

The "Try It" button implements the first part of the exercise (makes the subdirectories and moves and copies the files to their proper locations). The "Reset" button implements the second part of the exercise (puts all files back to the root directory and removes all of the subdirectories).

 

Note: In this sample program, the object variable for the FSO (mobjFSO) is declarted at the form (module) level. That way, it is available to all Subs and Functions in the form. The "New"  keyword is used, making the various methods and properties of the FSO  available without using a separate "Set" statement to instantiate it.

 

Private mobjFSO  As New FileSystemObject

 

The cmdTryIt_Click code, as well as a Sub called CopyOrMoveFiles (to facilitate the copying and moving of files) is shown below. The code is heavily commented to aid in the understanding of what the code is doing.

 

You will notice that two statements, "DoEvents" and "Refresh"  are used throughout the procedure.

 

The DoEvents statement "yields execution so that the operating system can process other events". DoEvents is typically used to break up processor-intensive operations (such as all the I/O this program is doing) so that the system does not appear to freeze up and so that you can do other things (such as run another program) while the VB program is running.

 

"Refresh" is actually a method of the form and could have been coded as "Me.Refresh" or "frmTest.Refresh". The Refresh method forces the form to repaint itself. The Refresh method was used to ensure that each "Print" message is displayed at the desired time (during processor-intensive operations, the form does not always automatically repaint itself when we want it to).

 

Private Sub cmdTryIt_Click()

 

    On Error GoTo cmdTryIt_Click_Error

   

    Cls

   

    ' Make the top-level subdirectories below the root with

    ' the CreateFolder method of the FSO ...

    mobjFSO.CreateFolder "A:\SYSTEM"

    mobjFSO.CreateFolder "A:\COMMAND"

    mobjFSO.CreateFolder "A:\EXECUTE"

    mobjFSO.CreateFolder "A:\INITIAL"

    mobjFSO.CreateFolder "A:\TEXT"

    mobjFSO.CreateFolder "A:\WRITE"

   

    ' Free up the OS for a sec and ensure message is displayed ...

    DoEvents

    Print "Top-level directories have been made."

    Refresh

   

    ' To faciliate the moving of the files to their proper directories, a Sub named

    ' CopyOrMoveFiles was written. The Sub takes four arguments: (1) source path,

    ' (2) target path, (3) file extension, and (4) a one-character code indicating

    ' whether the files should be moved ("M") or copied ("C"). The Sub is called six

    ' times, once for each file type to be moved from the root to its proper directory.

    CopyOrMoveFiles "A:\", "A:\SYSTEM", "SYS", "M"

    CopyOrMoveFiles "A:\", "A:\COMMAND", "COM", "M"

    CopyOrMoveFiles "A:\", "A:\EXECUTE", "EXE", "M"

    CopyOrMoveFiles "A:\", "A:\INITIAL", "INI", "M"

    CopyOrMoveFiles "A:\", "A:\TEXT", "TXT", "M"

    CopyOrMoveFiles "A:\", "A:\WRITE", "WRI", "M"

   

    ' Free up the OS for a sec and ensure message is displayed ...

    DoEvents

    Print "Files have been moved from root to top-level directories."

    Refresh

   

    ' Create the EXE_INI directory below the SYSTEM directory

    ' using the CreateFolder method ...

    mobjFSO.CreateFolder "A:\SYSTEM\EXE_INI"

    Print "Second-level directory for EXE and INI files has been made."

   

    ' Use the "CopyOrMoveFiles" Sub to copy the EXEs and INIs to the

    ' newly-created directory ...

    CopyOrMoveFiles "A:\EXECUTE", "A:\SYSTEM\EXE_INI", "EXE", "C"

    CopyOrMoveFiles "A:\INITIAL", "A:\SYSTEM\EXE_INI", "INI", "C"

   

    ' Free up the OS for a sec and ensure message is displayed ...

    DoEvents

    Print "Files have been copied to EXE_INI directory."

    Refresh

 

    ' Create the TXT_WRI directory below the INITIAL directory

    ' using the CreateFolder method ...

    mobjFSO.CreateFolder "A:\INITIAL\TXT_WRI"

    Print "Second-level directory for TXT and WRI files has been made."

    ' Use the "CopyOrMoveFiles" Sub to copy the TXTs and WRIs to the

    ' newly-created directory ...

    CopyOrMoveFiles "A:\TEXT", "A:\INITIAL\TXT_WRI", "TXT", "C"

    CopyOrMoveFiles "A:\WRITE", "A:\INITIAL\TXT_WRI", "WRI", "C"

   

    ' Free up the OS for a sec and ensure message is displayed ...

    DoEvents

    Print "Files have been copied to TXT_WRI directory."

    Refresh

   

    Print "Done."

 

    Exit Sub

 

cmdTryIt_Click_Error:

   

    MsgBox "The following error has occurred:" & vbNewLine _

         & "Error # " & Err.Number & " - " & Err.Description, _

           vbCritical, _

           "File System Commands Demo - Error"

 

End Sub

 

 

Private Sub CopyOrMoveFiles(pstrSourcePath As String, _

                            pstrTargetPath As String, _

                            pstrExtension As String, _

                            pstrCopyOrMoveCode As String)

 

' This Sub takes four arguments: (1) source path, (2) target path, (3) file extension,

' and (4) a one-character code indicating whether the files should be moved ("M") or

' copied ("C").

 

    Dim strCurrentFile  As String

    Dim strPattern      As String

    Dim strSourceFile   As String

    Dim strTargetFile   As String

   

    ' If the source path does not already have a backslash at

    ' the end of it, add one ...

    If Right$(pstrSourcePath, 1) <> "\" Then

        pstrSourcePath = pstrSourcePath & "\"

    End If

 

    ' If the target path does not already have a backslash at

    ' the end of it, add one ...

    If Right$(pstrTargetPath, 1) <> "\" Then

        pstrTargetPath = pstrTargetPath & "\"

    End If

   

    ' Create the "source pattern" by concatenating the source path, "*.", and

    ' the extension. For example, if "A:\" was passed in as the source path and

    ' "SYS" was passed in as the extension, the value of strPattern would be

    ' "A:\*.SYS".

    strPattern = pstrSourcePath & "*." & pstrExtension

 

    ' The coding for this part of the process is easier with the FSO. In the previous

    ' topic which used the native VB file processing statements, we had to use the

    ' "Dir" function in a loop and copy the files one at a time; the native "FileCopy"

    ' command cannot copy multiple files at once (i.e., a wildcard pattern cannot be

    ' used). If a "move" was specified, the files that were copied had to be deleted

    ' with the Kill statement (the Kill statement does support multiple files using a

    ' wildcard pattern). There is no specific statement to move files in the set of

    ' native VB file processing statements.

   

    ' On the other hand, the FSO has both a CopyFile and a MoveFile method, both of

    ' which support file specifications with a wildcard pattern, enabling you to

    ' copy or move multiple files at once.

 

    If pstrCopyOrMoveCode = "M" Then

        mobjFSO.MoveFile strPattern, pstrTargetPath

    Else

        mobjFSO.CopyFile strPattern, pstrTargetPath

    End If

 

End Sub

 

After the cmdTryIt_Click event procedure has run, the form should look like this:

 

 

 

The cmdTryIt_Click code, as well as a Sub called MoveFilesBackToRoot implements the follow-up part of the student exercise (to restore the disk back to its original state – i.e., all files back in the root with no subdirectories) is shown below. The code is heavily commented to aid in the understanding of what the code is doing.

 

Private Sub cmdReset_Click()

 

    On Error GoTo cmdReset_Click_Error

   

    Cls

   

    ' To faciliate the moving of the files from their individual directories back to

    ' the root and subsequently deleting the individual directory, a Sub named

    ' MoveFilesBackToRoot was written. The Sub takes two arguments: (1) the individual

    ' directory name, and (2) the file extension of the files to be moved.

   

    ' It should be noted that in the MoveFilesBackToRoot Sub, the FSO's DeleteFolder

    ' method is used to delete the individual directories. An important difference

    ' between the DeleteFolder method and the native VB RmDir statement is that

    ' with the DeleteFolder method, the folder to be deleted need NOT be cleared of

    ' files or subdirectories below it; whereas with RmDir, the directory to be

    ' deleted DOES have to be cleared first. For this reason, the "EXE_INI" directory

    ' made below the "SYSTEM" directory and the "TXT_WRI" directory below the "INITIAL"

    ' directory need not be cleared prior to deleting the top-level "SYSTEM" and

    ' "INITIAL" directories.

   

    MoveFilesBackToRoot "SYSTEM", "SYS"

    MoveFilesBackToRoot "COMMAND", "COM"

    MoveFilesBackToRoot "EXECUTE", "EXE"

    MoveFilesBackToRoot "INITIAL", "INI"

    MoveFilesBackToRoot "TEXT", "TXT"

    MoveFilesBackToRoot "WRITE", "WRI"

   

    Print "Done."

    Refresh

   

    Exit Sub

 

cmdReset_Click_Error:

   

    MsgBox "The following error has occurred:" & vbNewLine _

         & "Error # " & Err.Number & " - " & Err.Description, _

           vbCritical, _

           "File System Commands Demo - Error"

   

End Sub

 

 

Private Sub MoveFilesBackToRoot(pstrDirName As String, _

                                pstrExtension As String)

 

' This Sub takes two arguments: (1) the individual directory name, and (2) the file

' extension of the files to be moved.

 

    ' Use the CopyOrMoveFiles Sub to move the files with the specified extension

    ' from their "home" directory back to the root ...

    CopyOrMoveFiles ("A:\" & pstrDirName), "A:\", pstrExtension, "M"

   

    ' Delete the individual directory using the DeleteFolder method ...

    ' Note: The DeleteFolder method does NOT require that the files or subdirectories

    ' below it be cleared first prior to deleting it. For this reason, the "EXE_INI"

    ' directory made below the "SYSTEM" directory and the "TXT_WRI" directory below

    ' the "INITIAL" directory will not be cleared prior to deleting the top-level

    ' "SYSTEM" and  "INITIAL" directories.

    mobjFSO.DeleteFolder "A:\" & pstrDirName

   

    ' Free up the OS for a sec and ensure message is displayed ...

    DoEvents

    Print pstrDirName & " directory has been cleared; files moved back to root."

    Refresh

 

End Sub

 

After the cmdReset_Click event procedure has run, the form should look like this:

 

 

Download the VB project code for the example above here.

 

Sample Program 2

 

The second sample program combines the functionality of two sample program presented in the previous topics on reading and writing a fixed-width sequential file. The previous topics used the native VB commands, this topic will use the FSO.

 

Upon clicking the "Try It" button, the program first displays the records currently in the file. The user is then prompted to add records (an InputBox is used to prompt for each field, starting with the employee name):

 

 

The user enters the name, followed by the other fields with each successive prompt:

 

 

 

 

 

 

Once the fields that make up a record have been entered, that record is written to the file and is displayed on the form, and the next set of prompts begins:

 

 

When the user is done entering records, they would click "Cancel" on the InputBox when prompted for the name, and the prompting will stop. The resulting form will show all the records that were initially read, as well as all the records that were just entered:

 

 

The cmdTryIt_Click code is shown below. The code is heavily commented to aid in the understanding of what the code is doing.

 

Private Sub cmdTryIt_Click()

 

    ' Declare an object variable for the FSO itself, instantiating

    ' it by using the "New" keyword in the declaration.

    ' Declaration is made at the local level (i.e., within the

    ' Sub), as it will not be used in any other Sub in this program).

    Dim objFSO          As New Scripting.FileSystemObject

   

    ' Declare an object variable for the FSO TextStream object

    Dim objTextFile     As TextStream

   

    ' Filename-related declarations

    Dim strEmpFileName  As String

    Dim strBackSlash    As String

   

    ' Record and field name declarations

    Dim strEmpRecord    As String

    Dim strEmpName      As String

    Dim intDeptNbr      As Integer

    Dim strJobTitle     As String

    Dim dtmHireDate     As Date

    Dim sngHrlyRate     As Single

   

    ' set up the text file name

    strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")

    strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

   

    '**************************************************************

    '*** First portion of this sample program: Read and display the

    '*** records in the employee text file ...

    '**************************************************************

   

    ' Display headings prior to processing the file ...

    Print "The following records were read from the text file:"

    Print "EMP NAME"; _

          Tab(25); "DEPT"; _

          Tab(35); "JOB TITLE"; _

          Tab(60); "HIRE DATE"; _

          Tab(71); "HRLY RATE"

    Print "--------"; _

          Tab(25); "----"; _

          Tab(35); "---------"; _

          Tab(60); "---------"; _

          Tab(71); "---------"

   

    ' Using the OpenTextFile method of the FSO, set the TextStream object

    ' variable "objTextFile" to be a reference to the employee file that

    ' we want to process. The second argument of the OpenTextFile method

    ' (expressed as the FSO constant "ForReading") tells the system that

    ' we want to process the file in an input mode ...

    Set objTextFile = objFSO.OpenTextFile(strEmpFileName, ForReading)

   

    ' Set up a loop to process the text file until we reach end-of-file.

    ' The TextStream property "AtEndOfStream" enables us to test this.

    Do Until objTextFile.AtEndOfStream

        ' Read a "record" (line) from the TextStream object using the

        ' "ReadLine" method of the TextStream object ...

        strEmpRecord = objTextFile.ReadLine

        ' Break up the record into separate fields, as was done in previous

        ' sample programs ...

        strEmpName = Left$(strEmpRecord, 20)

        intDeptNbr = Val(Mid$(strEmpRecord, 21, 4))

        strJobTitle = Mid$(strEmpRecord, 30, 21)

        dtmHireDate = CDate(Mid$(strEmpRecord, 51, 10))

        sngHrlyRate = Val(Mid$(strEmpRecord, 61, 5))

        ' Display the contents of the fields ...

        Print strEmpName; _

              Tab(25); Format$(intDeptNbr, "@@@@"); _

              Tab(35); strJobTitle; _

              Tab(60); Format$(dtmHireDate, "mm/dd/yyyy"); _

              Tab(71); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

    Loop

   

    ' After processing all the records in the text file, close the file using the

    ' Close method of the TextStream object ...

    objTextFile.Close

   

    '****************************************************************

    '*** Second portion of this sample program: Read and display the

    '*** records in the employee text file ...

    '****************************************************************

   

    ' Display headings prior to processing the file ...

    Print

    Print "The following records were written to the text file:"

    Print "EMP NAME"; _

          Tab(25); "DEPT"; _

          Tab(35); "JOB TITLE"; _

          Tab(60); "HIRE DATE"; _

          Tab(71); "HRLY RATE"

    Print "--------"; _

          Tab(25); "----"; _

          Tab(35); "---------"; _

          Tab(60); "---------"; _

          Tab(71); "---------"

   

    ' Using the OpenTextFile method of the FSO, "re"-set the TextStream object

    ' variable "objTextFile" to be a reference to the employee file that

    ' we want to process. This time, the second argument of the OpenTextFile

    ' method (expressed as the FSO constant "ForAppending") tells the system that

    ' we want to process the file in an output mode, appending each new record

    ' to the end of the file ...

    Set objTextFile = objFSO.OpenTextFile(strEmpFileName, ForAppending)

   

    ' As in previous sample programs, set up an "input loop" to prompt the user

    ' for data.

    ' "Priming" input:

    strEmpName = InputBox("Enter name (or click Cancel to stop):")

   

    ' The loop will continue until the user clicks "Cancel" on the InputBox (which

    ' will cause the result variable of InputBox (strEmpName) to be set to a zero-

    ' length string ("") ...

    Do Until strEmpName = ""

        ' Prompt the user for each field:

        intDeptNbr = InputBox("Enter dept:")

        strJobTitle = InputBox("Enter job title:")

        dtmHireDate = InputBox("Enter hire date:")

        sngHrlyRate = InputBox("Enter hourly rate:")

        ' Create the record to be written by concatenating the input fields ...

        strEmpRecord = Left$(strEmpName & Space$(20), 20) _

                     & Format$(intDeptNbr, "@@@@") _

                     & Space$(5) _

                     & Left$(strJobTitle & Space$(21), 21) _

                     & Left$(Format$(dtmHireDate, "m/d/yyyy") & Space$(10), 10) _

                     & Format$(Format$(sngHrlyRate, "#0.00"), "@@@@@")

        ' Using the WriteLine method of the TextStream object,

        ' write the record to the file ...

        objTextFile.WriteLine strEmpRecord

        ' Display the contents of the record that was written on the form ...

        Print strEmpName; _

              Tab(25); Format$(intDeptNbr, "@@@@"); _

              Tab(35); strJobTitle; _

              Tab(60); Format$(dtmHireDate, "mm/dd/yyyy"); _

              Tab(71); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

        ' Start a new record by prompting for the employee name ...

        strEmpName = InputBox("Enter name (or click Cancel to stop):")

    Loop

   

    ' After adding the desired records, close the file using the

    ' Close method of the TextStream object ...

    objTextFile.Close

   

    ' Release the resources consumed by the objects by setting them to Nothing ...

    Set objTextFile = Nothing

    Set objFSO = Nothing

 

End Sub

 

Download the VB project code for the example above here.