Reading and writing files.

To read and write information to a file we can use two methods of the FileSystemObject object: The method CreateTextFile() takes up to three arguments: If the method successfully opened the file it returns a TextStream object that can be used to read from or write to the file. Once we created a file we can write to it using the same methods we used for StdIn object. The following code creates a file test.txt and writes a short sentence to it
var fs = new ActiveXObject("Scripting.FileSystemObject");
var file = fs.CreateTextFile("test.txt");
file.WriteLine("I'm just trying to write something to the file");
file.Close();

The method OpenTextFile() Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file. The general syntax of the method is

fs_object.OpenTextFile( filename [, iomode[, create[, format]]])
where In the following example we will open the file test.txt for appending and add a couple of lines in the file. If the file doesn't exist it will be created.
var ForAppending = 8;
var fs = new ActiveXObject("Scripting.FileSystemObject");
var file = fs.OpenTextFile("test.txt", ForAppending, true);
file.WriteLine("one more line");
file.WriteLine("last line");
file.Close();

To open a file use code like this

var ForReading = 1;
var fs = new ActiveXObject("Scripting.FileSystemObject");
var file = fs.OpenTextFile("test.txt", ForReading);

var msg = "";
msg += file.ReadLine() + "\n";
while( ! file.AtEndOfStream ){
   msg += file.ReadLine() + "\n";
}
file.Close();
WScript.Echo(msg);

Please note that we deal with open files (read or write) exactly the same way we dealt with the standard input/output streams, because they all are objects of the TextStream type.


References