Building WebApps  «Prev  Next»

Lesson 8Reading and outputting files
ObjectiveUse the FileSystemObject object to read and output a file.

Reading and outputting Files in ASP

Once a text file has been created, it's very useful to be able to access it through an ASP script. This technique is often used to import large amounts of data into the application. Reading a text file also involves using the FileSystemObject object, which has an OpenTextFile method. The OpenTextFile method has these parts:
  1. Object: (Required) Always the name of a FileSystemObject.
  2. Filename: (Required) String expression that identifies the file to open.
  3. Iomode: (Optional) Indicates input/output mode. Can be one of three constants,: ForReading (1), ForAppending (8), or (2) ForReading, which is the default.
  4. Create: (Optional) Boolean value that indicates whether a new file can be created if the specified filename doesn't exist (True to create the file, False not to create one). The default is False.
  5. Format: (Optional) If omitted, the file is opened as ASCII.
The snippet of code below shows a short example of using the object to read a text file through the OpenTextFile method.

<%
  Dim objFSO, objFile, objLogFile, currentLine, strFileName
  strFileName = "C:\log.txt"
  Set objFSO=Server.CreateObject("Scripting.FileSystemObject")
  if objFSO.FileExists(strFileName) then
       Set objLogFile = objFSO.OpenTextFile(strFileName, 1)
       while objLogFile.AtEndOfStream <> true
            currentLine = objLogFile.ReadLine
            Response.Write currentLine + "<br>"
       wend
  else
       Response.Write "Log file not found."
  end if
%>


Here is the same code segment with an explanation:
File Object Write
File Object Write



Write to File using ASP

File Object Write 1
Declare a Dim objFS0
  1. Declares variables needed to handle the file information. Assigns the name of the file to the strFileName variable
  2. Creates an instance of the File System Objects and assigns a reference to objFS0
  3. This statement verifies that the file exists. if it does not, a message should be displayed to the user
  4. Opens the text file in strFileName for reading, defined by the constant 1(2=write, 8 = append) Assigns a handle for the file to objLogFile
  5. While loop will continue executing until the End of File is encountered
  6. Reads a line from the text file and assigns it to current line . Information is read as a string.
  7. Appends a line break to the currentLine
  8. Message to be displayed if the file is not found.
It is good practice to clear the variables assigned to objects in order to free up system resources. At the end of the code you can add these statements: In the next lesson, you will write variables to and display a log file in the course project.
Set objLogFile = Nothing
Set objFSO = Nothing