Reading data of a file by ASP File system object

While reading the content of the file we can use three different ways to collect the data. One is by specifying number of chars we are interested in collecting or reading.

Response.Write OpenFileobj.Read(3)

The above line will collect 3 characters from the file to read the next 3 again we have to use the same command. As we are not aware of how many characters are present inside the file so we will use a loop to collect all the data in a set of 3 chars. Here we have to check that we have not reached the end of the file. We will get this error message

If there are two chars left then our last command should collect the two chars and should not try again. To do this we will use command OpenFileobj.AtEndOfStream . This will became true once the file end is reached.

Do While Not OpenFileobj.AtEndOfStream

We can also read line by line by changing the read command to ReadLine. Here is the code to read one line each time.

Response.Write OpenFileobj.ReadLine

Same way we can read all the content of the file by using a single command ReadAll like this

Response.Write OpenFileobj.ReadAll

This is to be used when the file we are reading is not big as this command uses lot of memory to store all the data.

<%
Dim OpenFileobj, FSOobj,FilePath
FilePath=Server.MapPath("text.txt") ' located in the same director
Set FSOobj = Server.CreateObject("Scripting.FileSystemObject")
if FSOobj.fileExists(FilePath) Then
Set OpenFileobj = FSOobj.OpenTextFile(FilePath, 1)

Do While Not OpenFileobj.AtEndOfStream
Response.Write OpenFileobj.ReadLine & "<br>"
Loop

OpenFileobj.Close
Set OpenFileobj = Nothing
Else
Response.Write "File does not exist"
End if
Set FSOobj = Nothing
%>