Write to a text file with ASP

This guide shows how to write to a text file on the server from an ASP (Active Server Pages) script on your Loopia Windows hosting. The example implements a small visit counter that reads a number from a text file, increments it, and writes it back. Just replace the name of the text file (textfile.txt) with the name you use for your own text file.

Note on error handling

Note that ON ERROR RESUME NEXT is used in the example below. It should be avoided in production code, because it causes errors to be silently ignored, which makes bugs hard to diagnose.

Example code

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