Home

Storing data in text file and reading and writing to a file is a very useful feature of any server side scripting language.

For example you can write down the comments made by users to end of every file using fso. Very advanced application can be created that access data to and from a text file. You can also store in binary mode, the choice is yours.

Fso, read and write to files in asp

Fso stands for File System Object. Here we will display how fso is used to read and write to a file. We will also use form to capture data from the browser and write it to the file.

It this example, a function named cnt() reads and write a number value to a file named cnt.txt (the file should already exist). This is a simple counter to figure out how many times a particular page has been displayed.

 
<%

'Calling the function here
response.write "Loaded: " & cnt & " times."

Function cnt()

'Create the FSO object
Set myFSO = Server.CreateObject("Scripting.FileSystemObject")

'Get the file
Set myFile = myFSO.OpenTextFile(server.mappath("cnt.txt"))
oldNum = CLng(myFile.ReadLine)
myFile.Close

newNum = oldNum + 1 ' add 1 to the old number

Set myFile = myFSO.OpenTextFile(server.mappath("cnt.txt"),2,true)
myFile.WriteLine(newNum)

myFile.Close

cnt = newNum
End Function

%>

 

[Download Sample Code]