Reading text file line by line, with resetting position to beginning of file

BugMan

Well-known member
Joined
Dec 27, 2010
Messages
52
Location
Tallahassee FL
Programming Experience
10+
I'm reading a text file with StreamReader, line by line. If a condition is met, then I do an operation and then start reading the file again from the first line. I realize I could close and then re-open the file, but surely this would be very slow.

I could do this easily in VB6, but pulling my hair out trying to do this in vB.net. It seems that 'Seek' is the function to use, but it doesn't work. Does anybody see what the problem is?

I've seen other examples, where it works, but you must open it a different way -- with a file number. At this point, I'll take any way I can get it!

thanks in advance.



VB.NET:
Imports System.IO

Dim I as Integer
Dim LineText as String
Dim ioFile As New StreamReader("C:\MyDir\MyTextFile.txt")

        For I  = 1 To 100 

            'How to set position in file back to 1st line or character in file?
            
            'Seek(?, 1)   'doesn't work

            'this doesn't work either
            'ioFile.BaseStream.Seek(0, SeekOrigin.Begin)  

             'read text file line by line, when condition met, do operation
            Do While ioFile.Peek <> -1
                LineText = ioFile.ReadLine()
                'if LineText = this, then do that
            Loop
         
           

        Next I%

        ioFile.Close()
 
You would call Seek on or, more simply, set the Position of the BaseStream, then call DiscardBufferedData on the StreamReader. The StreamReader may actually read more Bytes from the underlying FileStream than are required for the text returned, so you must empty the internal buffer as well as reset the file pointer.

Also, use the StreamReader's EndOfStream property rather than calling Peek as it is more natural.

Having said all that, could it not be more efficient to simply read the file once into a String array and then read that array multiple times? Unless your file is too large to store in local memory, I'd suggest that that would be a better way to go because disk I/O is one of the slowest things you can do.
 
Having said all that, could it not be more efficient to simply read the file once into a String array and then read that array multiple times? Unless your file is too large to store in local memory, I'd suggest that that would be a better way to go because disk I/O is one of the slowest things you can do.

Hmmm. Wow. The files are not that big, few hundred K at most, so reading them into an array from the beginning would be much better. Darn, wish I would have thought about that!

Thanks very much JM!
 
Back
Top