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>"
       Response.Write "Log file not found."
  end if

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

Write To File using ASP
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