Jul 04 2002

Writing to a textfile in ASP

Posted by admin under Filehandling

This example uses the opening function described here.

Here we open a file, reads it content ( just a number ), increment the number and writes it back to the file ( this is a little hit counter )

<%
Dim oFile
Dim nNumber
	
Set oFile = File_OpenExisting( "c:\test.txt", File_OpenForReading  )
If oFile Is Nothing Then
	Response.Write "FATAL ERROR"
Else
	If oFile.AtEndOfStream = True Then
		nNumber = 0
	Else
		nNumber = CInt(oFile.ReadLine())
	End If
	nNumber = nNumber + 1
	oFile.Close
	Set oFile = File_OpenExisting( "c:\test.txt", File_OpenForWriting ) 
	oFile.WriteLine nNumber	
	oFile.Close
End If
%>

If you don't know the exact path to the file ( like c:\www\hello.txt ) - you might just know the file is located under the /files/ subdirectory at your webhost then you need to convert the path using Server.MapPath. Check out our String functions section for examples.