Building WebApps  «Prev  Next»

Lesson 7Writing a text file
ObjectiveUse the FileSystemObject to create and write a file.

Writing to Text File

As you learned in the previous lesson, The FileSystemObject object has several methods. Of these, we will need to use the CreateTextFile method to create a file.
The CreateTextFile method returns a TextStream object, which has its own methods, including WriteLine and Close. The WriteLine method writes a string to the text file plus a new line character.

TextStream Read and Write Methods

Read(n) Reads n characters from the text file; returns a character string
ReadLine Reads an entire line; does not include the new line character. Returns a character string.
ReadAll Reads the entire file; returns a character string.
Close Closes the file when you are finished.
FileExists Does the file exist (True/False)? This can be used as part of an If/Then statement.
Write(string) Writes a string to the open text file.
WriteLine(string) Writes a string to the text file plus a new
line character.
WriteBlankLines(n) Writes n new line characters to the file.


Set fileSys = Server.CreateObject("Scripting.FileSystemObject")
textFileName = "c:\testfile.txt" 
Set textStream = fileSys.CreateTextFile(textFileName, True)
textStream.WriteLine("Just writin' a little text.")
textStream.Close

Here is the same code segment with an explanation:
Text Write
The diagram shown above describes how to create a text ffile.

Writing ASP Text File
The text file that you create could be written to a protected directory that users cannot access, or it could become an order confirmation that is displayed to the user or inserted into an email using stored user information.
Be aware that writing files for multiple users or writing multiple files for the same user over multiple sessions can significantly increase the complexity of your task.


Writing to Files for Multiple Users

A key issue related to multiple users/multiple sessions is creating files with a unique name for each user and/or session. You might consider using SessionID, but Session IDs are, as we learned earlier, not necessarily unique. One possible solution would be to use the SessionID combined with some other identifier(s), such as the date and time or an application variable or ID generated from specific user information.
Another issue arises when you attempt to use the same file to store information from different ASP pages, since you may overwrite data in an existing file or attempt to append information to a file that has not yet been created. You can, however, check to see if a file already exists for the user with the FileExists method. If it does not, you use the CreateTextFile method to create it; if it does, use the OpenTextFile method to open it and append data