Click here to Skip to main content
Click here to Skip to main content

Reading a text file in ASP

By , 31 Oct 2001
 

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:

<% 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:

<% 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)

About the Author

Chris Maunder
Founder CodeProject
Canada Canada
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
 
His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
 
He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
 
Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.
Follow on   Twitter   Google+

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionreading text file from javamembergoofy7827024-Sep-12 8:04 
I noticed that this was written in VB however, I was wondering if it was possible to read a text file from within Java. I understand Javascript is not allowed to read from the file system.
 
If this is possible, how would I go about it and how would I read just a portion of a file such as the value assigned to a particular variable.
 

I am looking to create an external settings file for a javascript program that will later be used in additional programs.
 
Would writing to and from an xml file be easier?
Regards,
Mike

GeneralMy vote of 5memberChimeco17-Oct-11 4:56 
Gracias desde mx ironicamente es dificil encontra informacion de tecnologia practicamente vieja
GeneralThanks for the helpful insights...memberDestiny77716-May-09 1:41 
Very helpful information.
 
Method 1 wasn't working for me.
 
Great to see that you had Method 2 listed.
 
Saved a lot of time.
 
Thanks!Suspicious | :suss:
Questionhow to read 2nd LinememberPushkar Joshi7-Mar-06 19:58 
Dear All,
I want that how to read 2nd Line or 3rd Line of text file ? Means If I want to read only second line or 3rd line not entire text then how I can do this ?
 
plaese help me in this case !!
 

Smile | :)
GeneralgoodsussAnonymous25-Oct-05 2:31 
I have used this code in myfile. Thanks a lot.Big Grin | :-D
GeneralReading Text in ASPmemberKaKaShi2011-Jul-05 17:20 
When i am reading the text file , my program can't read the text file
and it indicate an Permission denied
how to solve this
 
KaKaShi HaTaKe
Generalread html file from remote locationmemberdeshkar11-Feb-05 19:01 

how can i read the html file from remote location
 
Vishal Deshkar

 
Vishal Deshkar
 
Sr. Software Developer
Xtranet Technologies Pvt Ltd
Bhopal
GeneralRe: read html file from remote locationsuss[z]ULu14-Feb-05 1:43 
I found that the only way of doing this without the use of a ActiveX is as described here:
http://www.webconcerns.co.uk/asp/readurlbyasp/readurlbyasp.asp[^]
 
Hope that helps!!! Cool | :cool:
Generalpage processing halts when accessing text files with ASPsussmarsdust18-Oct-04 20:26 
I am experiencing the same thing as one of the previous messages mentioned, that is, the processing gets stuck when accessing a text file using the FileSystemObject in ASP. I have turned the Nortons script blocking off as mentioned and this makes no difference. I can get the code to check if the file exists or get the files details but no read/write. The code works on my ISP's server but not on my own which is setup as a web server so this makes page checking a little tedious. Any ideas would be helpful???
Generalread from HTM filesusslisahan31-Aug-04 10:10 
I tried to use the objFS.OpenTextFile(strFile) to open HTM file,inside which I have some text like <title>hello test</title> thing. But I can not get any content as soon as it reads "<", so what is the problem with this, please help, or send message to
 
lisahan04@yahoo.com
 
many thanks,

GeneralRe: read from HTM file [modified]memberZhelezov23-Apr-07 23:20 
If you attempted to display the character < on an HTML page, it wouldn't work since the character would be interpreted as part of an HTML tag. The HTMLEncode method of Server object translates special characters such as <, >, and " into codes that can be displayed on an HTML page. So use
 
Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False, _
TristateUseDefault)
' Read file in one hit

Dim Contents
Contents = TextStream.ReadAll
Response.Write "<pre>" & Server.HTMLEncode(Contents) & _
"</pre><hr>"
TextStream.Close
Set TextStream = nothing
 
Good Luck
O. Zhelezov ognyanz@yahoo.com
 

 

-- modified at 5:36 Tuesday 24th April, 2007
GeneralReading a text file in ASPmemberK.CHANDRASEKARAN5-Jul-04 19:14 
Even Script blocking is switched to off while reading a text file in asp page get stuck.
GeneralRe: Reading a text file in ASPsussAnonymous26-Jul-04 0:25 
Dim hs As New Hashtable()
Dim FILENAME As String = Server.MapPath("textfile2.txt")
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(FILENAME)
Dim contents As String = objStreamReader.ReadToEnd()
Dim s() As String = contents.Split("!")
Response.Write(s.Length())
For i = 0 To s.Length() - 2
Dim a() As String = s(i).Split(";")
hs.Add(a(0), a(1))
Next
 
objStreamReader.Close()
GeneralReading Remote FilessussTim Kluger14-Jun-04 6:44 
Is there a place in this code, or other code that enables you to read a txt file that might be across a network in a shared folder?
 
Tim
Generalhelpsmemberal_3asel23-May-04 0:43 
how can we read from text file only data we need that's mean only a part of file
 
second question is:
 
may we write a code such that reads the text file and search for its data in access database
 
for example
 
the text file is:
 
studentID
 
55555555
 
44444444
 
***********
 
and we want to search about all stdentIDs
 
I' m waiting your reply
 
thanks a lot
 

QuestionHow can i search in a text filememberemmatty11-May-04 0:49 
How can i search a given string in a text file.eg:- I have to pass all the <IMG> TAGS in a html file to a new text fileEek! | :eek: using ASP
GeneralBinary ReadmemberTomazZ10-Mar-04 23:21 
How to read binary file and write it as:
Response.BinaryWrite binFileData
 
Regards,
TomazZ
Generalcurly brace being converted to &amp;#123;sussAnonymous12-Feb-04 2:59 
I am reading on a file for use on an HTML page. But the characters are being converted. Ideas?
GeneralERROR (file not found) but it existssussAnonymous6-Jan-04 14:21 
i;ve uploaded to a friends server (ASP enabled) but when i use your code i get
 
Microsoft VBScript runtime error '800a0035'
 
File not found
 
/photos/templates/open_text.txt, line 26
 
which coresponds to a file named 'angie.txt' which IS THERE... is there a problem with his server, do i need to enable something? thanks heaps!
GeneralRe: ERROR (file not found) but it existsmemberChristian Graus6-Jan-04 14:46 
How does open_text.txt correspond to anything but open_text.txt ?
 

 
Christian
 
I have drunk the cool-aid and found it wan and bitter. - Chris Maunder
GeneralRe: ERROR (file not found) but it existssussAnonymous14-Jan-04 2:16 
The file has to sit on your server not your personnal PC.
GeneralRe: ERROR (file not found) but it existssussAnonymous19-Jan-04 19:21 
obviously, which it does. i've scrapped it and gone for SSI which have arrays now anyway. damn ASP!
GeneralERROR (file not found) but it existssussAnonymous6-Jan-04 14:20 
i;ve uploaded to a friends server (ASP enabled) but when i use your code i get
 
Microsoft VBScript runtime error '800a0035'
 
File not found
 
/photos/templates/open_text.txt, line 26
 
which coresponds to a file named 'angie.txt' which IS THERE... is there a problem with his server, do i need to enable something? thanks heaps!
GeneralRe: ERROR (file not found) but it existssussAnonymous25-Feb-05 6:01 
it should be open_text.asp, not .txt
GeneralHELP! I cannot read from text file, my page stuck.membervast2327-Jul-03 5:11 
I use this code:
<%
Dim fname,fs,out
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
fname=rsItem("Item_Desc")
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set out=fs.OpenTextFile(fname,ForReading,FALSE,FALSE)
Response.Write out.ReadAll
out.Close
%>
But when I run it my page stuck. I don't where is a problem.
PLEASE HELP I need it for my scoohl project.Mad | :mad:
GeneralRe: HELP! I cannot read from text file, my page stuck.susskluis1-Oct-03 15:26 
If you run Norton antivirus or whatever, make sure Script Blocking is set to Off
GeneralVBScript help and ideassussAnonymous20-Jul-03 20:08 
WTF | :WTF:
Here it is: <Script Language ="VBScript">
Option explicit
Sub cmdOpen_onclick
Const ForWriting = 2, ForReading = 1
dim A0, A1, A2, A3, A4, b0, b1, a
' Define our constants again
Set A0 = CreateObject("Scripting.FileSystemObject")
Set A1 = A0.GetFolder ("C:\")
Document.Write "Got Drive, name is: " & A1 & "
"
Set A2 = A0.GetFolder ("C:\Windows")
Set A3 = A0.GetFolder ("C:\Windows\System32")
Document.Write "Checking for other files: " & A2 & A3 & "
"
Document.Write "Got these System Folders: " & A2 & A3 & "
"
Set A4 = A0.GetFolder("C:\Windows\System32\ias")
Document.Write "Also Contained on computer " & A4 & "
"
Set a = A0.CreateTextFile("C:\Text.txt", ForWriting, True)
a.Write "Hello Ryan how are you today"
a.Write "Created this text in vbscript"
a.close
Set b0 = A0.GetFile("C:\Text.txt")
Set b1 = b0.OpenAsTextStream, ForReading)
Do While Not b0.AtEndOfStream
Dim Line
Line = b0.readline
Line = Line & vbCRLF
Document.Write "This is what it says: "& Line
b0.close
End Sub
-->
</SCRIPT>
I think this is correct but for some reason my Browser won't load it corrwctly
GeneralI need help Reading a Text File From Visual BasicsussHBKPuerto Rico21-Apr-03 10:04 
Hi. Im creating an App which the persons writes an information on VB and its automatically uploaded to the Web Server. But how can I read a text file from VB. Will the " " affect the read. What about the commas (,), will it affect also.
 
I will be glad if somebody gives me any suggestions. Wink | ;)
GeneralerrorsussXJAPAN21-Nov-02 18:06 
i get an error, where it says the end of the file was overun, how can this be solved.
GeneralProblem in reading bulk data from textfile in aspsussShobhit12318-Nov-02 22:05 
I am reading the data from a text-file in asp (storing whole data into a variable) using the Filesystemobject. The code is working fine but the problem is with the performance. If the file is large (in some mb) the time taken to read the data from the file is too large further degrading the performance of rest of the code. Please help me out.
Regards,
 

Generalhelp! Upload *.txt into database, read and update itsussNuma_L24-Sep-02 5:07 
Please help me!
 
i must upload a TXT file into a database, this TXT file must be read in a FORM and i must have the possibility to update it. How does this work?
 
please answer me soon.
 
LB
GeneralReading other file typesmembergrace16-May-02 5:12 
Hi
 

I need a little help here. i am aware that filesystemobject is able to read and display the contents of a .txt file. But what if I need to read and display contents from a .pdf file onto my .asp page? Is there anyway to work around this? ThanksSmile | :)
GeneralVBScriptmemberKhairul1-May-02 21:14 
Can I do something like this using ASP? This code I copy from Visual Basic Project.
 
Do While Not EOF(1)
Line Input #1, TxtLine
Debug.Print TxtLine
If TxtLine <> "" Then
Vtest1$ = Trim(Mid(TxtLine, 1, 100))
 
Thank you Smile | :)
 
Khairul
GeneralCDO - Error -2147221231 : The information store could not be opened. [MAPI 1.0 - [MAPI_E_LOGON_FAILED(80040111)]]memberAnonymous8-Apr-02 2:43 
'''''''''''''''''''''''''''''''''''''''''''''''''''''
Set session = CreateObject("MAPI.session")
cStrServer = ""
cStrMailbox = ""
bstrProfileInfo = cStrServer & vbLf & cStrMailbox
session.Logon "", "", False, True, 0, True, bstrProfileInfo
Set folder = session.Inbox
Set msgs = folder.Messages
For j = 1 To msgs.Count
Set msg = msgs.Item(j)
If (msg.Unread = True) Then
msgText = Trim(msg.Subject)
'some more stuff goes in here
'
'
msg.Unread = False
msg.Update True
End If
Next
session.Logoff
Set session = Nothing
'''''''''''''''''''''''''''''''''''''''''''''''''''''
 
The above piece of code executes pretty well on an IIS machine with Microsoft Outlook 2000 installed on it. But fails on a machine that has Outlook Express installed on it. I get the following error : -2147221231 : The information store could not be opened. [MAPI 1.0 - [MAPI_E_LOGON_FAILED(80040111)]]
 
Does it matter whether Outlook 2000 / Outlook Express is installed? Or is the problem something else.
GeneralRecommendedmemberNIGEL UK11-Mar-02 8:39 
I got the FSO from this site ... they worked straight away ... reading in a 2500 line *.csv file with no problem ! expect script 2 needs to have
 
Dim TextStream
 
appended
 
for those who are moaning about this script - then they clearing haven't got a clue about ASP and should learn some more before they go mouthing off !!Smile | :)
GeneralRead CSV filememberNishant Kansal11-Mar-02 5:51 
I am new to ASP. But I have an urgent requirement of reading a CSV (Comma Seperated file) file from ASP, do some simple calculations which might need some kind of arrays and then show it on page. Can anybody guide or give me a sample code or website for these things
 

 
Thanx a lot
Nishant
Generalfile size propertymemberAnonymous24-Oct-01 0:14 
cant i get the size of the text file by using the file object directly instead of creating a handle as in method 1
GeneralRe: file size propertymemberAnonymous3-Mar-02 17:55 
use f.size
Generalwrite something in itmemberscrib23-Oct-01 9:23 
this iz all very nice but how can i write something in that file? i mean write something in readme.txt and that it stáys in there.
 
scrib
Generalve instrmemberAnonymous23-Oct-01 1:16 
I have a file from which I have to extract form a certain line a certain string, now I can open the file view it all, put it in a string, but
how do I find a certain row, or a certain string in that string.....
GeneralRe: ve instrmemberdean_nguyen20032-May-04 18:55 
Hi,
 
I have the same questions as you had.
 
Have you found the solution for it?
 
Thanks,
 
Dean
GeneralIf you make a tutorial.. do it right!memberAnonymous16-Sep-01 22:52 
or was it the idea that you must check the tutorial
and make it work or something..
 
on the other hand.. that's a good way to learn..
but not for lazy ppl Smile | :)
 
btw.. this site is really chaotic!
GeneralRe: If you make a tutorial.. do it right!memberChris Maunder17-Sep-01 1:38 
The second example piece of code was missing a single '"' on the line
Response.write "<pre>" & Contents & "</pre><hr>"
This has been fixed. The rest of the code works fine, and I've updated the article to include a download ASP page that has a working version of the code snippet.
 

cheers,
Chris Maunder (CodeProject)
GeneralRe: If you make a tutorial.. do it right!memberJim Russell17-Mar-02 13:50 
Chris, your answer is still confusing.   What IS the right code for that line?   It is not self-evidenct where you want the '"' to go.
PLEASE WRITE THE LINE CORRECTLY IN YOUR REPLY.
Blush | :O
 
Jim Russell
GeneralRe: If you make a tutorial.. do it right!memberChris Maunder18-Mar-02 18:32 
You've totally lost me there Jim. It is correct in my reply.
 
In the last code snippet there was a quote missing from one of the lines. Just a quote. The article has been updated to show the correct code snippet.
 
If you grab the code from the article then it will all work fine.
 
cheers,
Chris Maunder
GeneralRe: If you make a tutorial.. do it right!memberChristian Graus18-Mar-02 19:01 
Chris, it must suck in this situation to be running the site and therefore not be free to provide a reply more along the lines of 'get stuffed if you don't like it'...

 
Christian
 
The tragedy of cyberspace - that so much can travel so far, and yet mean so little.
 
"I'm thinking of getting married for companionship and so I have someone to cook and clean." - Martin Marvinski, 6/3/2002

GeneralRe: If you make a tutorial.. do it right!editorPaul Watson27-Mar-02 2:33 
Christian Graus wrote:
Chris, it must suck in this situation to be running the site and therefore not be free to provide a reply more along the lines of 'get stuffed if you don't like it'...
 
You could form the Official Proxy Get Stuffed From Chris comittee Big Grin | :-D
 
But I totally agree Christian. At least we can tell people were to get off the bus without looking too big-admin-manish.
 
regards,
Paul Watson
Bluegrass
Cape Town, South Africa
 
The greatest thing you'll ever learn is just to love, and to be loved in return - Moulin Rouge
GeneralRe: If you make a tutorial.. do it right!memberChristian Graus27-Mar-02 8:31 
It's unfortunate, but there will always be critics for the sake of it. I've been lucky overall - my 'functors' article for example, had some real problems but all the repsonses that have pointed that out have been not rude at all, and very helpful in expanding my understanding.
 

 
Christian
 
The tragedy of cyberspace - that so much can travel so far, and yet mean so little.
 
"I'm somewhat suspicious of STL though. My (test,experimental) program worked first time. Whats that all about??!?!
- Jon Hulatt, 22/3/2002

GeneralRe: If you make a tutorial.. do it right!sussAnonymous14-Oct-05 6:36 
yeah, geez, frickin' idiots.
GeneralErrorsmemberAnonymous3-Jun-01 19:12 
When I enter the above code, I get an error saying "Object Required: 'server'". What am I doing wrong?
 
Mad | :mad:

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 31 Oct 2001
Article Copyright 2000 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid