Search code examples
vbscriptasp-classicdo-whilefilesystemobject

How to Rerun the TextStream.AtEndOfStream


I'm successfully running the code below to display a text file to the browser, line by line:

<% 
    Filename = "/pages/test.txt"
    Set FSO = server.createObject("Scripting.FileSystemObject")
    Filepath = Server.MapPath(Filename)

    Set file = FSO.GetFile(Filepath)
    Set TextStream = file.OpenAsTextStream(1, -2)  

    Do While Not TextStream.AtEndOfStream  
            Line = TextStream.readline
            Response.Write Line & "<br>"
    Loop 

    Set TextStream = nothing
    Set FSO = nothing
%>

I'd like to run the Do While Not TextStream.AtEndOfStream loop one more time, right before the Set TextStream = nothing statement.

Turns out I cannot "just" copy the Do While loop and place it below the first instance. There are no results from the TextStream anymore.

Is there a way to reset the TextStream object back to the beginning of the stream?

I could store the lines in an array and utilize that, but I wanted to see if there was an easier route.


Solution

  • Unfortunately, there's no way to manually position the pointer in a TextStream object. You can Close the TextStream and reopen it. Or, you can just read the file once into an array, as you implied. Considering you're outputting the entirety of the file to a web page, I'll assume it's not incredibly large and, therefore, storing it in an array would not be too memory intensive.

    ' Create an array containing each line from the text file...
    a = Split(file.OpenAsTextStream(1, -2).ReadAll(), vbCrLf)
    
    For i = 0 To UBound(a)
        Response.Write a(i) & "<br>"
    Next
    
    ' Repeat the process...
    For i = 0 To UBound(a)
        Response.Write a(i) & "<br>"
    Next
    

    You could even replace the line endings with <br> and write it in one operation:

    strText = Replace(file.OpenAsTextStream(1, -2).ReadAll(), vbCrLf, "<br>")
    
    Response.Write strText
    Response.Write strText    ' Write it again