Home

ASP ADVANCED

This section describes how to read and write to a text file.  There are many uses for a text file, including these common ones:

  • A custom log.  Use a text file to record the activities of the visitors to your Web site.  You can record such information as their IP addresses, the browsers they used, and the amount of time they spent at your Web site.

  • Form data.  Use a text file to store the information collected from an HTML form.  For example, if a user enters registration information into an HTML form, you can store that information in a text file.

  • Tip of the Day.  Store a list of tips for using your Web site in a text file, and randomly retrieve and display them on a Web page.  

Writing to a Text File

To create and write to a text file, you can use the FileSystemObj ect and TextStream objects.  First, you must create an instance of the FileSystemObject object.  Next, you call the CreateTextFile( ) method of the FileSystemObject object to return an instance of a TextStream object.  Finally, you use the Writeline( ) method of the TextStream object to write data to the file.  Here's an example:  

<%
Set MyFile0biect=Server.Create0biect("Scripting.FileSystemObject")
Set MyTextFile=MyFile0bject.CreateTextFile("c:\mydir\test.txt")  
MyTextFile.WriteLine("Hello There!")  
MyTextFile.Close  
%>

This example creates a file named test. txt with the path c: \mydir\ test. txt.  The WriteLine( ) method is used to send the single line of text Hello There! to the file.  Finally, the instance of the TextStream object is closed to preserve system resources.  Each of these steps is described in more detail in the following paragraphs.

The CreateTextFile( ) method is used to create the new text file.  When this method is called, a TextStream object is returned.  This method has one required parameter and two optional ones:

  • Filespecifier.  Specifies the path of the file to create.  If a directory in the path doesn't exist, the error File not found is returned.

  • overwrite.  This parameter is optional.  By default, it has the value TRUE. A call to CreateTextFile( ) automatically overwrites any preexisting file with the same name.  If this parameter is set to FALSE, an error occurs if the file already exists.

  • Unicode.  This parameter is optional.  By default, it has the value FALSE, which indicates that a file using the ASCII character set should be created.  If set to TRUE, a file using the Unicode character set will be created.

After a file has been created with the CreateTextFile( ) method, you can use the TextStream object to write to the file.  When using the TextStream object for writing, you can use the following methods:

  • write(string).  This method writes a string to the file.

  • writeLine([string]).  This method writes a string to the file and adds a newline character.  The string argument is optional.  If no string is specified, a newline character is written to the file.

  • WriteBlankLines(lines).  This method writes the specified number of blank lines (newline characters) to the file.

  • close.  This method is used to close an open TextStream file and free up resources.

For example, to create a text file containing the text Hello world!  32 times in a row, you would use the following script:

<%
Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile=MyFileObject.CreateTextFile("c:\mydir\test.txt")
FOR i=1 to 32
MyTextFile.WriteLine("Hello World!")
NEXT
MyTextFile.Close
%>

Reading and Appending Data from a Text File

To read from a text file, you first need to create an instance of the FileSystemObject object.  Next, you use the OpenTextFile( ) method to return an instance of the TextStream object.  Finally, you can use the ReadLine method of the Textstream object to read from the file.  Here's an example:

<%
set MyFile0biect=Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile=MyFileObject.OpenTextFile("c:\mydir\test.txt")
WHILE NOT MyTextFile.AtEndOfStream
Response.Write(MyTextFile.ReadLine)
WEND
MyTextFile.Close
%>

This script reads everything from the text file named test.txt.  It outputs the contents of this file to the browser.  If the file doesn't exist, the error File Not Found is returned. (In the next section, you learn how to detect whether a file exists.)

The WHILE...WEND loop in this example moves through the contents of the file until the end of the file is reached.  The AtEndOfStream property has the value FALSE until the loop moves to the end of the file.

The following properties of the TextStream object are useful when reading from a text file:

  • AtEndOfLine.  This property indicates whether the end of a particular line in a text file has been reached. When the newline character is detected, this property has the value TRUE.

  • AtEndOfStream.  This property indicates whether the end of the entire text file has been reached.  It can have the value TRUE or the value FALSE. 

  • column. This property indicates the current character position in a line.  The property returns an integer value.

  • Line.  This property indicates the current line in a file.  The property returns an integer value.

Instead of using the ReadLine method to read through the contents of a file, you can use the Read( ) method.  The Read( ) method returns a specified number of characters from an open text file.  Following is an example of how to use this method:

<%
Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject")
set MyTextFile=MyFileObject.OpenTextFile("C:\mydir\test.txt")
WHILE NOT MyTextFile.AtEndOfLine
Response.Write(MyTextFile.Read(1))
WEND
MyTextFile.Close
%>

This script retrieves the first line from a text file, one character at a time.  The AtEndOfLine property detects when the end of the first line of the text file has been reached.  The Read( ) method reads one character at a time from the text file.

The following methods are useful when reading data from a text file (continued on the next page):

  • Read(characters).  This method reads the specified number of characters from the text file.

  • ReadLine.  This method reads a single line from the text file. (The newline character is not returned.)

  • ReadAll.  This method retrieves the entire contents of the TextStream file.

  • Skip(characters).  This method skips the specified number of characters in an open text file.

  • SkipLine.  This method skips a single line in an open text file.

  • close.  This method closes an open TextStream file and frees up resources.

Normally, the OpenTextFile( ) method is used for retrieving data from a text file.  However, you can also use this method to append new data to a text file, like this:

<%
Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile=MyFileObject.OpenTextFile("c:\mydir\browser.log", 8, TRUE)
MyTextFile.WriteLine(Request.ServerVariables("HTTP_USER_AGENT"))
MyTextFile.Close
%>

This script creates a log of the browsers being used at a Web site. Whenever the script is executed, the type of browser used to request the page is recorded in a text file.  This browser information is retrieved from the ServerVariables collection.

The preceding script appends the browser type to the end of the text file named browser.log.  If the file browser.log doesn't exist when this script is first executed, the file is created automatically.  This is accomplished by using two parameters of the OpenTextFile( ) method: the IOMode and the Create parameters.

The following list describes all the parameters of the OpenTextFile( ) method:

  • FileSpecifier.  Specifies the path to the file to open for reading or appending.

  • IOMode.  Optional parameter indicating whether the file should be opened for reading, writing, or appending.  The default value is 1 for reading.  To open a file for writing, set this value to 2. To open a file for appending, set this value to 8.

  • Create.  Optional parameter indicating whether the file should be created if it doesn't exist.  By default, the value of this parameter is FALSE.

  • Format.  Optional parameter that specifies the format of the file.  By default, a file uses the ASCII character set.  However, you can use the Unicode character set by passing the value -1, or the system default by passing the value -2.

Sample Application

This section provides a sample application of the methods used for reading and writing to files.  As I write this, Amazon.com (the online bookstore) is holding a competition to write a collaborative online story.  The first part of the story was entered by John Updike.  Each day, visitors to the Amazon.com Web site submit new sentences to add to the story.  One sentence is selected every day, and the winner receives $ 1,000.  The story is being written collaboratively.

This competition is a great idea.  It attracts repeat visitors to the Amazon.com Web site, and it has generated a tremendous amount of publicity.  You may want to add something similar to your Web site.  Listing below shows a simple example of how you could do this.

<%
IF NOT Request.Form("NextLine")=" " THEN
Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile=MyFileObject.OpenTextFile("c:\mydir\TheStory.txt", 8, TRUE)
MyTextFile.WriteLine(Request.Form("NextLine"))
MyTextFile.Close
END IF
%>
<HTML>
<HEAD><TITLE> Online Story </TITLE></HEAD>
<BODY>
<HR>
<%
Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject")
Set MyTextFile=MyFileObject.OpenTextFile("c:\mydir\TheStory.txt")
WHILE NOT MyTextFile.AtEndOfStream
Response.Write("&nbsp;&nbsp;"&MyTextFile.ReadLine)
WEND
MyTextFile.Close
%>
<HR>
<H3>Enter a new line for the story: </H3>
<FORM METHOD="POST" ACTION="story.asp">
<INPUT NAME="NextLine" TYPE="TEXT" SIZE=70>
<INPUT TYPE="SUBMIT" VALUE="Submit Sentence">
</FORM>
</BODY>
</HTML>

This Active Server Page contains two scripts.  The first script executes when a new sentence has been submitted.  If a new sentence exists, it's appended to the file named TheStory.txt.

The second script is used to display the contents of the TheStory.txt file.  Each line in the file is outputted.  The lines are separated by two nonbreaking space characters so that the sentences will be divided by spaces when displayed.

The remainder of the Active Server Page contains an HTML form for submitting the next line in the story.  The Active Server Page posts the form contents to itself.  For this to work, you must name the Active Server Page story.asp.

Before you use this Active Server Page for the first time, you need to create a text file named TheStory.txt.  The first sentence of the story needs to be entered into this file.  If you want to restart the story, simply c!ear this file and enter a new first sentence.