Previous Section Table of Contents Next Section

Reading and Writing Text Files

The FSO provides basic functionality for reading from, and writing to, text files. If you think of a text file as one long string of characters, you'll have an idea of how the FSO views text files. In fact, that long string of characters is what the FSO calls a TextStream. TextStream objects are how you get text into and out of text files.

The FSO has two basic methods for creating a TextStream: CreateTextFile and OpenTextFile. Both methods require you to provide a filename, and allow you to specify optional parameters, such as whether to overwrite any existing file when creating a new one. Here's an example.


Dim oFSO, oTS

Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")

Set oTS = oFSO.CreateTextFile("c:\test.txt")

oTS.WriteLine "Hello, World!"

MsgBox "All Done!"

oTS.Close

As you can see, the result of the CreateTextFile method is a TextStream, which is assigned via the Set command to variable oTS. TextStream objects have some properties and methods all their own. First, the methods:

  • Write writes one or more characters to the file.

  • WriteLine writes one or more characters and follows them with a carriage return/linefeed combination, thus ending the line as you would in Notepad when you press Enter.

  • Close closes the TextStream.

  • Read reads a specified number of characters from a TextStream.

  • ReadLine reads an entire line of characters-up to a carriage return/linefeed.

  • ReadAll reads the entire TextStream.

One useful property of a TextStream is AtEndOfStream, which is set to True when you've read all the way through a text file and reached its end.

Files must be opened either for reading, writing, or appending. When a file is opened for reading, you can only use the Read, ReadLine, and ReadAll methods; similarly, when the file is opened for writing or appending, you can only use Write or WriteLine. Of course, you can always use Close.

NOTE

Appending a file simply opens it and begins writing to the end of the file, while leaving the previous contents intact. This can be useful for writing messages to an ongoing log file.


Another way to open a file is to use the OpenAsTextStream method of a File object that represents the file. This technique also returns a TextStream object. The OpenAsTextStream method allows you to specify how you want the file opened-for reading, writing, or appending.

graphics/arrow.gif Reading and Writing Files

Listing 12.5 is a robust example script that demonstrates how to read and write text files from within a script. I'll use these same techniques at the end of the chapter, when I'll show you how to create a script that scans IIS log files for Active Server Pages errors.

Listing 12.5. FileWork.vbs. This script creates a file, writes text to it, and then reads the text back in again.

Dim sFileName, oFSO, oTS, sText

Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")



sFileName = InputBox("Enter the full path and " & _

 "name of a file to be created.")



If oFSO.FileExists(sFileName) Then

 If MsgBox("This file exists. OK to overwrite?", _

  "Are you sure?" & _

  4 + 32) <> 6 Then

  MsgBox "Script aborted."

  WScript.Exit

 Else

  Set oTS = oFSO.CreateTextFile(sFileName,True)

 End If

End If



oTS.WriteLine "Script log file:"

oTS.WriteLine "Started " & Now()

oTS.WriteLine "Finished" & Now()

oTS.Close



MsgBox "Finished making file. Feel free to edit it," & _

 " and click OK to continue."



Set oTS = oFSO.OpenTextFile(sFileName)

sText = oTS.ReadAll

oTS.Close



MsgBox "Your file contains: " & vbCrLf & vbCrLf & _

 sText

This script is ready to run on any system.

graphics/arrow.gif Reading and Writing Files-Explained

This is a straightforward script, and it's a good review of VBScript in general because it combines some important elements that you've already learned. It starts by declaring some variables and creating a new FSO.


Dim sFileName, oFSO, oTS, sText

Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")

Next, it uses an input box to get a filename.


sFileName = InputBox("Enter the full " & _



 "path and name of a file " & _

 "to be created.")

Next, the script checks to see if the file exists. If it does, it uses a message box to ask permission to overwrite the file. Notice that this is a more complete version of MsgBox() than I usually use in examples. This version provides a title for the message box and specifies that it should contain a question mark icon and Yes and No buttons (4 is the question mark, 32 is Yes/No). I had to look those values up in the VBScript documentation. Finally, MsgBox is being used as a function-if the user clicks Yes, the function will return a 6 (also from the documentation), so this code checks to see if a 6 was returned.


If oFSO.FileExists(sFileName) Then

 If MsgBox("This file exists. OK to overwrite?", _

  "Are you sure?" & _

  4 + 32) <> 6 Then

  MsgBox "Script aborted."

  End

If the user clicks Yes, the script creates a new text file. Notice the True, which tells CreateTextFile to overwrite any existing file, if there is one.


 Else

  Set oTS = oFSO.CreateTextFile(sFileName,True)

 End If

End If

The script uses the WriteLine method to add some text to the file before closing it.


oTS.WriteLine "Script log file:"

oTS.WriteLine "Started " & Now()

oTS.WriteLine "Finished" & Now()

oTS.Close

Finally, the script displays a message. If you want, open the text file and edit it-that'll prove that the script is reading back the text file in the next step.


MsgBox "Finished making file. Feel free to edit it," & _

 " and click OK to continue."

In the next step, I reuse the same variable to reference a new TextStream, this time reopening the same file by using OpenTextFile. I use ReadAll to load the entire file into a variable, and then close the TextStream. I finish by displaying the contents of the file in a message box.


Set oTS = oFSO.OpenTextFile(sFileName)

sText = oTS.ReadAll

oTS.Close



MsgBox "Your file contains: " & vbCrLf & vbCrLf & _

 sText

This example is a good reference for you to use when you start working with text files in your own scripts.

    Previous Section Table of Contents Next Section