Reading Files
August 14, 2000
So now we have some nice user information stored in a file, which
happily works as a simple database. Now suppose a user comes along
and wants to view all your wonderful visitors. We've got to spit that
information out somehow. Since we don't have a database with
nicely structured columns, we'll have to get clever to output
the results we want.
We know that in the file we just created, the first line is the user's
name, the second line is their homepage, and the third line is their
email address. Every subsequent user who comes along will also have
their information stored in this way, so that every third line will
contain the same type of information. Knowing that, we can now write
some code to grab the info:
<%
' create the fso object
set fso = Server.Createobject("Scripting.FileSystemObject")
path = "c:\temp\test.txt"
' open the file
set file = fso.opentextfile(path, 1) <-- For reading
Now let's grab each line and format it accordingly:
do until file.AtEndOfStream
Response.write("Name: " & file.ReadLine & " ")
Response.write("Home Page: " & file.ReadLine & " ")
Response.write("Email: " & file.ReadLine & "<p>")
loop
' close and clean up
file.close
set file = nothing
set fso = nothing
%>
|
NOTE:
We did a very simple output here, but note that you can
place the information wherever and however you like, including
in table cells and
DHTML forms.
|
If you've created and written your file properly, this little loop
will properly list everyone in your database. The ReadLine method reads
one line up to the newline character. Subsequent calls to ReadLine
will read the next lines. AtEndOfStream is a property of the TextStream
object that lets
us know when we've hit the end of the file.
Suppose for some reason we didn't format the file correctly. If a
user only has 2 lines instead of 3 describing their info, then we
will get some errors here. Our loop gets the next 3 lines
in the file and if there are not 3 more lines to be had, your page
will get mad and throw an error like:
Server object error 'ASP 0177 : 800a003e'
at you. So be sure to add some error
checking to make sure you're not skipping or inserting too many
lines.
Writing Files
The wonders of the File System Object
Permissions
|