Write to a text file with ASP

If you want to write to a text file on the server you can use this code. This example shows how to use a text file that is a small counter. Just replace the name of the text file (textfile.txt) to the name you have on your text file.

Note that ON ERROR RESUME NEXT is used and it should be avoided in production code because it implies that errors are ignored.

<%
on error resume next
' creates an instance of an server object
set fso = createobject("scripting.filesystemobject")
' finds the text file
set act = fso.opentext file(server.mappath ("textfile.txt"))
' reads the content from the text file,
' if the text file is missing it will be created further down
counter = clng(act.readline)
' adds one
counter = counter + 1
' closes the server object
act.close

' creates a new text file if it does not already exist a file
Set act = fso.Createtext file(server.mappath("textfil.txt"), true)
' writing the new content to the text file
act.WriteLine(counter)
' closes the server object
act.Close

' prints the content of the text file to the screen
Response.Write counter
%>
Was this article helpful?

Related Articles