Working With Files

See Also

You can work with files in Visual Basic by using the new object-oriented FSO objects such as Copy, Delete, Move, and OpenAsTextStream, among others, or by using the older existing functions such as Open, Close, FileCopy, GetAttr, and so forth. Note that you can move, copy, or delete files regardless of their file type.

For more information on usage of the older existing functions, see "Processing Files with Older File I/O Statements and Functions" in this chapter. The rest of this section describes using the new FSO objects, methods, and properties to work with files.

There are two major categories of file manipulation:

Creating Files and Adding Data with File System Objects

There are three ways to create a sequential text file (sometimes referred to as a "text stream"). One way is to use the CreateTextFile method. To create an empty text file:

Dim fso As New FileSystemObject, fil As File
Set fil = fso.CreateTextFile("c:\testfile.txt", True)

Note   The FSO object model does not yet support the creation of random or binary files. To create random and binary files, use the Open command with either the Random or Binary flag. Full information on how to manipulate random and binary files is contained in "Using Random File Access" and "Using Binary File Access" in this chapter.

Another way is to use either the OpenTextFile method of the FileSystemObject object with the ForWriting flag set:

Dim fso As New FileSystemObject, ts As New TextStream
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting)

Or you can use the OpenAsTextStream method with the ForWriting flag set:

Dim fso As New FileSystemObject, fil As File, ts As TextStream
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("test1.txt")
Set fil = fso.GetFile("test1.txt")
Set ts = fil.OpenAsTextStream(ForWriting)

Adding Data to the File

Once the text file is created, you can add data to it in three steps:

  1. Open the text file for the writing of data.

  2. Write the data.

  3. Close the file.

To open the file, you can use either of two methods: the OpenAsTextStream method of the File object, or the OpenTextFile method of the FileSystemObject object.

To write data to the open text file, use either the Write or WriteLine methods of the TextStream object. The only difference between Write and WriteLine is that WriteLine adds newline characters to the end of the specified string.

If you want to add a newline to the text file, use the WriteBlankLines method.

To close an open file, use the Close method of the TextStream object.

Here's an example of how to open a file, use all three write methods to add data to the file, then close the file:

Sub Create_File()
    Dim fso, txtfile
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
    txtfile.Write ("This is a test. ") ' Write a line.
    ' Write a line with a newline character.
    txtfile.WriteLine("Testing 1, 2, 3.") 
    ' Write three newline characters to the file.      
    txtfile.WriteBlankLines(3) 
    txtfile.Close
End Sub

Reading Files with File System Objects

To read data from a text file, use the Read, ReadLine, or ReadAll methods of the TextStream object:

Task Method
Read a specified number of characters from a file Read
Read an entire line (up to, but not including, the newline character) ReadLine
Read the entire contents of a text file ReadAll

If you use the Read or ReadLine method and you want to skip to a particular portion of data, you can use the Skip or SkipLine method.

The resulting text of the read methods is stored in a string which can be displayed in a control, parsed by string operators (such as Left, Right, and Mid), concatenated, and so forth.

Note   The vbNewLine constant contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage-return/linefeed). Be aware that the ends of some strings may have such nonprinting characters.

Example

Sub Read_Files()
    Dim fso As New FileSystemObject, txtfile, _
      fil1 As File, ts As TextStream
    Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
    MsgBox "Writing file"
    ' Write a line.
    Set fil1 = fso.GetFile("c:\testfile.txt")
    Set ts = fil1.OpenAsTextStream(ForWriting)
    ts.Write "Hello World"
    ts.Close
    ' Read the contents of the file.
    Set ts = fil1.OpenAsTextStream(ForReading)
    s = ts.ReadLine
    MsgBox s
    ts.Close
End Sub

Moving, Copying, and Deleting Files

The FSO object model has two methods each for moving, copying, and deleting files:

Task Method
Move a file File.Move or
FileSystemObject.MoveFile
Copy a file File.Copy or
FileSystemObject.CopyFile
Delete a file File.Delete or
FileSystemObject.DeleteFile

Example

This example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both directories.

To run this example, make sure that you have directories named \tmp and \temp in the root directory of drive C.

Sub Manip_Files()
    Dim fso as New FileSystemObject, txtfile, fil1, fil2
    Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
    MsgBox "Writing file"
    ' Write a line.
    txtfile.Write ("This is a test.")
    ' Close the file to writing.
    txtfile.Close
    MsgBox "Moving file to c:\tmp"
    ' Get a handle to the file in root of C:\.
    Set fil1 = fso.GetFile("c:\testfile.txt")
    ' Move the file to \tmp directory.
    fil1.Move ("c:\tmp\testfile.txt")
    MsgBox "Copying file to c:\temp"
    ' Copy the file to \temp.
    fil1.Copy ("c:\temp\testfile.txt")
    MsgBox "Deleting files"
    ' Get handles to files' current location.
    Set fil1 = fso.GetFile("c:\tmp\testfile.txt")
    Set fil2 = fso.GetFile("c:\temp\testfile.txt")
    ' Delete the files.
    fil1.Delete
    fil2.Delete
    MsgBox "All done!"
End Sub