Click here to Skip to main content
15,860,859 members
Articles / Web Development / IIS

Reading a text file in ASP.

Rate me:
Please Sign up or sign in to vote.
4.96/5 (15 votes)
18 Mar 2009CPOL 760.9K   4.1K   54   67
How to read a text file on a server using VBScript in ASP

One of the most important tasks in any programming language is the ability to read and write files. The steps involved in ASP are no different than many other languages:

  1. Specify the location of the file
  2. Determine if the file exists
  3. Get a handle to the file
  4. Read the contents
  5. Close the file and release any resources used

File I/O in ASP can be done using the FileSystemObject component. When opening a text file you simply open it as a text stream, and it is this text stream that you use to access the contents of the file.

The FileSystemObject allows you to perform all file and folder handling operations. It can either return a file which can then be opened as a text stream, or it can return a text stream object directly.

In the following I present two different methods. The first method gets a file object and uses that to open the text stream, and the second method opens the text stream directly from the FileSystemObject.

Method 1:

ASP
<% Option Explicit

Const Filename = "/readme.txt"    ' file to read
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

' Create a filesystem object
Dim FSO
set FSO = server.createObject("Scripting.FileSystemObject")

' Map the logical path to the physical system path
Dim Filepath
Filepath = Server.MapPath(Filename)

if FSO.FileExists(Filepath) Then

    ' Get a handle to the file
    Dim file    
    set file = FSO.GetFile(Filepath)

    ' Get some info about the file
    Dim FileSize
    FileSize = file.Size

    Response.Write "<p><b>File: " & Filename & " (size " & FileSize  &_
                   " bytes)</b></p><hr>"
    Response.Write "<pre>"

    ' Open the file
    Dim TextStream
    Set TextStream = file.OpenAsTextStream(ForReading, TristateUseDefault)

    ' Read the file line by line
    Do While Not TextStream.AtEndOfStream
        Dim Line
        Line = TextStream.readline
    
        ' Do something with "Line"
        Line = Line & vbCRLF
    
        Response.write Line 
    Loop


    Response.Write "</pre><hr>"

    Set TextStream = nothing
    
Else

    Response.Write "<h3><i><font color=red> File " & Filename &_
                       " does not exist</font></i></h3>"

End If

Set FSO = nothing
%>

Method 2:

ASP
<% Option Explicit

Const Filename = "/readme.txt"    ' file to read
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

' Create a filesystem object
Dim FSO
set FSO = server.createObject("Scripting.FileSystemObject")

' Map the logical path to the physical system path
Dim Filepath
Filepath = Server.MapPath(Filename)

if FSO.FileExists(Filepath) Then

    Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False, TristateUseDefault)

    ' Read file in one hit
    Dim Contents
    Contents = TextStream.ReadAll
    Response.write "<pre>" & Contents & "</pre><hr>"
    TextStream.Close
    Set TextStream = nothing
    
Else

    Response.Write "<h3><i><font color=red> File " & Filename &_
                   " does not exist</font></i></h3>"

End If

Set FSO = nothing
%>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
GeneralRe: If you make a tutorial.. do it right! Pin
Chris Maunder18-Mar-02 18:32
cofounderChris Maunder18-Mar-02 18:32 
GeneralRe: If you make a tutorial.. do it right! Pin
Christian Graus18-Mar-02 19:01
protectorChristian Graus18-Mar-02 19:01 
GeneralRe: If you make a tutorial.. do it right! Pin
Paul Watson27-Mar-02 2:33
sitebuilderPaul Watson27-Mar-02 2:33 
GeneralRe: If you make a tutorial.. do it right! Pin
Christian Graus27-Mar-02 8:31
protectorChristian Graus27-Mar-02 8:31 
GeneralRe: If you make a tutorial.. do it right! Pin
Anonymous14-Oct-05 6:36
Anonymous14-Oct-05 6:36 
GeneralErrors Pin
3-Jun-01 19:12
suss3-Jun-01 19:12 
GeneralRe: Errors Pin
Chris Maunder17-Sep-01 1:36
cofounderChris Maunder17-Sep-01 1:36 
Generalrunnning batch files with asp Pin
14-May-01 11:03
suss14-May-01 11:03 
GeneralRe: runnning batch files with asp Pin
13-Sep-01 2:54
suss13-Sep-01 2:54 
Questionwhat a sloppy piece of sh*t Pin
sdff31-May-00 10:16
sdff31-May-00 10:16 
AnswerRe: what a sloppy piece of sh*t Pin
21-Feb-02 5:32
suss21-Feb-02 5:32 
Questionwhere do i put the code? Pin
slightly_new31-May-00 10:05
slightly_new31-May-00 10:05 
Questionwhere do i put the code? Pin
slightly_new31-May-00 10:00
slightly_new31-May-00 10:00 
AnswerRe: where do i put the code? Pin
TNo10-Oct-00 10:14
TNo10-Oct-00 10:14 
Questionwhere do i put the code? Pin
slightly_new31-May-00 10:00
slightly_new31-May-00 10:00 
AnswerRe: where do i put the code? Pin
24-May-01 10:24
suss24-May-01 10:24 
GeneralWhy low rating Pin
Pete17-Apr-00 21:13
Pete17-Apr-00 21:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.