Working with Files

The FileSystemObject includes methods for creating and manipulating text files. You can create a new file, append to or overwrite an existing file, read an existing file into a script, move or copy a file from one location to another, and delete a file.

The TextStreamObject

When you create a text file you normally want to be able to populate the file with lines of text, either creating a new file or appending lines to an existing file. Or, you may only want to read lines of text from an existing file as input to a script. All of these activities are provided through the TextStreamObject. A TextStreamObject is created through the FileSystemObject. There are two creation options available when instantiating this object.

Creating Text Files. Use the CreateTextFile method of the FileSystemObject to create a new text file into which you can write lines of text. This can be an entirely new file or an overwrite of an existing file. This method assigns the newly created text file to a TextStreamObject, thereby providing access to its properties and methods.

Set TextStreamObject = FileSystemObject.CreateTextFile("path" [,True|False])

The TextStreamObject is a name you supply for your newly created TextStreamObject, FileSystemObject is the name of an existing FileSystemObject, and "path" is the full path to the new file, including the file name. The parameter True (the default) permits overwrite and replacement of an existing file with the same name.

Here, for example, is the pair of lines required to create a new text file, replacing, if necessary, an existing file of the same name:

<%
Set FSObj = Server.CreateObject("Scripting.FileSystemObject")
Set TSObj = FSObj.CreateTextFile("d:\eCommerce\Logs\LogFile.txt")
%>

Opening Text Files. Use the OpenTextFile method of the FileSystemObject to open an existing file. The file can be opened for reading only, for writing, or for appending.

Set TextStreamObject = FileSystemObject.OpenTextFile("path" [,1|2|8])

Again, the TextStreamObject is a name you supply for your newly created TextStreamObject, FileSystemObject is the name of an existing FileSystemObject, and "path" is the full path to the new file, including the file name. The final numeric parameter determines whether 1 the file is opened for reading only (the default), 2 the file is opened for overwriting, or 8 the file is opened for appending.

Here, for example, is the pair of lines required to open an existing text file that is read (only) for input into the script:

<%
Set FSObj = Server.CreateObject("Scripting.FileSystemObject")
Set TSObj = FSObj.OpenTextFile("d:\eCommerce\Logs\LogFile.txt")
%>

Although not coded here, you should check for the existence of a file before trying to open it. Otherwise, ASP will produce an error.

Writing to Files

When you create a new file it is normally because your script needs to write something to the file. The TextStreamObject includes several methods to write to a new file or to overwrite an existing file.

Method Purpose
TextStreamObject.WriteLine(variable|number|"string") Writes a line of text including script variables, numeric values, or strings. The line ends with a line break character.
TextStreamObject.Write(variable|number|"string") Writes text characters including script variables, numeric values, or strings. No line break character is written at the of the text.
TextStreamObject.WriteLine Writes a line break character only.
TextStreamObject.WriteBlankLines(n) Writes n line break characters only.

One reason for creating a text file from a script would be to log user activities at your site. The following is a fairly trite example, but it illustrates how a script can record user activities that otherwise would go unnoticed. This script logs visitors who have arrived at this page, recording the date, time, IP Address, and browser.

<%
TheDate = Date
TheTime = Time
IPAddress = Request.ServerVariables("REMOTE_ADDR")
Browser = Request.ServerVariables("HTTP_USER_AGENT")

Set FSObj=Server.CreateObject("Scripting.FileSystemObject")

If Not FSObj.FileExists("d:\eCommerce\Logs\LogFile.txt") Then
  FSObj.CreateTextFile("d:\eCommerce\Logs\LogFile.txt")
End If

Set TSObj = FSObj.OpenTextFile ("d:\eCommerce\Logs\LogFile.txt", 8)
TSObj.WriteLine(TheDate & "," & TheTime & "," & IPAddress & "," & Browser)
TSObj.Close
%>

The four items to be logged are captured as variables (for convenience in handling) at the beginning of the script. Then a FileSystemObject (FSObj) is created. To take care of the situation of the very first visitor, the original file is created if it doesn't already exist. Then a TextStreamObject (TSObj) is created to open the file (LogFile.txt) for appending (8). A line is written as a comma-delimited list of current date, current time, IP address, and browser data. The TSObj is closed (rather than waiting for the end of the page) because it is reopened below.

Each time you leave and return to this page a new entry is created. You might want to do this several times to create a log entry for yourself which you can view below.

Reading From Files

The TextStreamObject includes several methods to read from a file, possibly for display of the contents on a Web page.

Method Purpose
variable = TextStreamObject.ReadLine Reads a complete line of text into a variable.
variable = TextStreamObject.ReadAll Reads the entire contents of a file into a variable.
variable = TextStreamObject.Read(n) Reads n characters from the file into a variable.
TextStreamObject.SkipLine Skips a line of text in the file.
TextStreamObject.Skip(n) Skips n characters in the file.

A TextStreamObject also provide properties that are needed when reading lines and characters from a file.

Property Purpose
TextStreamObject.AtEndOfStream Returns True if the file pointer is beyond the last character (line) of the file.
TextStreamObject.AtEndOfLine Returns True is the file pointer is beyond the last character on a line.
TextStreamObject.Line Returns integer indicating the current line position in the file.
TextStreamObject.Column Returns integer indicating the current character position on the line.

The following script, for example, reads and displays the lines of text from the LogFile.txt. These lines include your visit(s) to this page.

<%
Set FSObj=Server.CreateObject("Scripting.FileSystemObject")

Set TSObj = FSObj.OpenTextFile ("d:\eCommerce\Logs\LogFile.txt")
Count = 0
Do While Not TSObj.AtEndOfStream
  LineIn = TSObj.ReadLine
  Response.Write(LineIn & "<br>")
  Count = Count + 1
Loop
TSObj.Close

If Count = 10 Then
  FSObj.DeleteFile("d:\eCommerce\Logs\LogFile.txt")
End If
%>

The TSObj points to the log file that is opened by the FSObj as a read-only file. We're not checking for an existing file since the previous script creates one if it doesn't exist. A simple loop is established to iterate through each of the lines of the file, checking for an AtEndOfStream condition to determine if all lines have been read. For each line, the TSObj uses its ReadLine method to input an entire line of text and assign it to variable LineIn. Then LineIn is written to the page. After the entire file is read, the TSObj is closed. Just to keep the file from getting too large, a counter is established and the file is deleted after recording 10 visits.

The following lines are the output from this script, written as-is to the page. We could have gotten fancy with the formatting, but this is just a log file.

12/24/2002,9:30:07 PM,68.1.144.101,Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)
12/24/2002,9:32:27 PM,68.1.144.101,Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)

Deleting Files

In a like manner to folders, files can be deleted by applying the FileSystemObject's DeleteFile() method. Again, be sure to check that the file exists before trying to delete it.

<%
Set FSObj=Server.CreateObject("Scripting.FileSystemObject")

If FSObj.FileExists("d:\eCommerce\Logs\LogFile.txt") Then
  FSObj.DeleteFile("d:\eCommerce\Logs\LogFile.txt")
  Response.Write("File deleted.<br>")
Else
  Response.Write("File missing.<br>")
End If
%>

Copying and Moving Files

A file can be copied or moved from one folder to another by using the FileSystemObject's CopyFile and MoveFile methods. The techniqes are the same as copying and moving folders, so you are referred to the previous page for those techniques. In the examples, simply replace CopyFolder with CopyFile and replace MoveFolder with MoveFile.