Reading Text Files in WSH - Reading methods
(Page 2 of 4 )
Any time you start thinking about working with files, you should automatically be thinking of WSH’s FileSystemObject. This is WSH’s way of allowing us to work with files and folders. So, naturally, we’ll begin our script by connecting to the FileSystemObject.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\addresses.txt", 1)
Do Until objFile.AtEndOfStream
strContents = strContents & objFile.Read(1)
Loop
Wscript.Echo strContents
objFile.Close
This simple code snippet opens a text file and reads it to the end one character at a time. Let’s take a look at the methods we used.
object.OpenTextFile Filename [, Iomode[, Create[, Format]]]
object.Read(Int)
In the second line, the OpenTextFile method opens the text file ForReading and returns it as a TextStream object. The second parameter accepts an Iomode constant depending on how we want to open the file. The default is ForReading.
Table 1: Constant Values for Iomode Attribute |
Constant | Value | Description |
ForReading | 1 | Read-Only |
ForWriting | 2 | Allow writing, overwrite contents |
ForAppending | 8 | Allow writing, append to file rather than overwrite |
|
Table 2: Tristate Values for Format Attribute |
Constant | Value | Description |
TristateTrue | -1 | Unicode |
TristateFalse | 0 | ASCII |
TristateUseDefault | -2 | Use system default |
Next, set up a loop to move through the text file. The AtEndOfStream property tells our script when it reaches the end of the text stream. The Read method is used to read the contents of the text file one character at a time.
The Read method returns a string containing the characters read from a text file. It accepts a single integer for a parameter indicating how many characters to read.
The TextStream Object’s Read method will return all characters it finds including whitespace characters such as carriage returns and line feeds.
The example script ends by Echoing back the entire text file as one string. Finally, the Close method is used to close the text stream.
Next: More methods >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer