Saturday, May 10, 2008

Vbscript Filesystemobject

Writen by Shaun Vermaak

One of the handy uses of the FileSystemObject is to manipulate text files. In this article I will discuss the methods related to creating, modifying and reading text files. This is especially useful when gathering information or logging the progress of a task.

The role of the FileSystemObject in working with text file is to return a TextStream object which in turn has the methods required to read and write data to text files. The TextStream can be opened in one of three modes namely read, write and append.

To enable the use of friendly names for these modes add the following constants to your script:

Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8

Next step is to create an instance of the FileSystemObject:

Set objFSO = CreateObject("Scripting.FileSystemObject")

It is important to understand that whether you read, write or append to a text file the OpenTextFile method will be used. This is because the FileSystemObject returns a TextStream object which in turn exposes the methods needed to work with text files.

Textstream in read mode:

Set objTextFile = objFSO.OpenTextFile("c:somelocationsometextfile.txt", ForReading)

Textstream in write mode:

Set objTextFile = objFSO.OpenTextFile("c:somelocationsometextfile.txt", ForWriting, True)

Textstream in append mode:

Set objTextFile = objFSO.OpenTextFile("c:somelocationsometextfile.txt", ForAppending, True)

Read text file line for line:

Do Until objTextFile.AtEndOfStream strLine = objFile.ReadLine Loop

Read entire text file:

Do Until objTextFile.AtEndOfStream strLine = objFile.ReadAll Loop

Write line to a text file:

objTextFile.WriteLine("Hallo world")

After working with text file it is important to close the file.

objTextFile.Close

Note that the True value that is present in the write and append mode means that the text file should be created if is doesn't already exist.

0 comments: