Reading & Writing to a Text File

Here is the content of a text file (writefile.txt) that's being read and placed onto this page:

This is text that's being read from a text file. This file can contain any type of text content, including html.

This can come in quite handy, as you can include text files on a web page, then have a web form that submits to the text file to update it. If you have a page that has information that changes frequently, and if you don't want to use a database to carry that information, using a text file is a viable alternative.

Here is the code that reads the text file:

 <%
    Set fs = CreateObject("Scripting.FileSystemObject")
    filename=server.mappath("/kathi/test/writefile.txt")
	Set readfile=fs.OpenTextFile(filename,1,False)
    Do until readfile.AtEndOfStream
        Text=readfile.readline
        If Text="" then
            response.write "<p>"
        Else
            response.write Text 
        End If
    Loop
    readfile.close
    set readfile=nothing
%>
And here is the code that can write to the file:
  <%
    Text = request("Text")
    filename=server.mappath("/kathi/test/writefile.txt")
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set writefile = fs.OpenTextFile(filename, 2, True)
    writefile.writeline(Text)
    writefile.Close
    set writefile=nothing
    set fs=nothing
 %>
 
You'll notice that in the first example, there's the number 1, and in the second there's the number 2. You can also use the number 8. Here's what each does:

1: Opens file for reading. You can't write to this file.

2: Opens file for writing. You can't read this file. Anything written to this file will overwrite the previous contents.

8: Opens the file for appending; the previous contents is not overwritten.

You'll also notice that the first example has the word "False" in it while the second has "True" in it. True means that the file should be created if it doesn't already exist, while false means that a new file should not be created if it doesn't already exist.