Reading and Writing Files with the VBScript FileSystemObject
By Stephen Bucaro
Scripts are (usually) small interpreted (meaning they don't get compiled) programs that you
can write using a simple text editor like Windows Notepad. VBScript stands for "Visual Basic
Script", which means it's written in Microsoft's easy to understand Visual Basic language.
The scripts are interpreted and executed by a program called the "Windows Scripting Host",
(WSH) which is installed on Windows computers by default.
It's easy to run a VBScript in the WSH, all you have to do is give the text file containing the
code a the .vbs file extension, then double-click on the file name. When you run a VBScript
it has access to the VBScript runtime objects. Reading and writing files uses two of these
objects: the FileSystemObject gives your script access to the computer's file system,
the TextStream object lets your script open, read, and write to text files.
To access the computer's file system, you must create a FileSystemObject with
the CreateObject method:
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
The FileSystemObject's CreateTextFile method creates a text file and returns a
TextStream object that can be used to read or write to the file:
Dim objFSO, objTextFile
Set objTextFile = objFSO.CreateTextFile(filename, overwrite, unicode)
The filename argument specifies the path and name of the file. The overwrite
argument is a Boolean value that specifies whether you can overwrite an existing file (true = overwrite,
false = do not overwrite).
The unicode argument specifies whether the file will be Unicode (a 32 bit standard for
encoding multiple international languages) or ASCII (a 7 bit code for encoding English) (true = Unicode
false = ASCII).
The FileSystemObject's OpenTextFile method opens an existing text file and returns
a TextStream object that can be used to read or write to the file:
Dim objFSO, objTextFile
Set objTextFile = objFSO.OpenTextFile(filename, mode, create, unicode)
The filename argument specifies the path and name of the file. The mode argument
requires a constant value (1 to open the file for reading; 2 to open the file writing; 8 to open the
file for appending).
The create argument is a Boolean value that specifies whether a new file should be
created if the specified file does not exist (true = create false = do not create).
The unicode argumment specifies whether the file will be opened in Unicode format
or ASCII format (true = Unicode false = ASCII).
TextStream Object Methods
Once the file is opened you use one of the following methods to read from or write to the file:
ReadAll reads the entire text file and returns a text string.
Dim fileText
fileText = objTextFile.ReadAll
ReadLine reads one line of text from a file. It reads up to, but does not include the
new-line character.
Dim fileText
fileText = objTextFile.ReadLine
|