StreamReader.Seek(0, Begin)

J

Joan Reddy

Can anyone tell me why this code doesn't work for setting the pointer to the
begining of a file stream?
This is driving me crazy.

At the end of Main1, sString2 is the second line of the file, as if the Seek
never worked.
Shouldn't sString1 and sString2 each contain the first line of the file?

To fix this (as in Main2), I need to create a new reader. Is this
documented behavior, or is this a bug??

Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Sub Main1()
Dim oFileStream As FileStream
oFileStream = New FileStream("c:myfile.txt",
FileMode.Open,FileAccess.Read)
Dim oReader As StreamReader
oReader = New StreamReader(oFileStream)
Dim sString1 As String
sString 1 = oReader.ReadLine()
oFileStream .Seek(0, SeekOrigin.Begin)
Dim sString2 = oReader.ReadLine()
MsgBox(sString1, sString2)
End Sub

Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Sub Main1()
Dim oFileStream As FileStream
oFileStream = New FileStream("c:myfile.txt",
FileMode.Open,FileAccess.Read)
Dim oReader As StreamReader
oReader = New StreamReader(oFileStream)
Dim sString1 As String
sString 1 = oReader.ReadLine()
oFileStream .Seek(0, SeekOrigin.Begin)
oReader = New StreamReader(oFileStream)
Dim sString2 = oReader.ReadLine()
MsgBox(sString1, sString2)
End Sub
 
D

David Browne

Joan Reddy said:
Can anyone tell me why this code doesn't work for setting the pointer to
the begining of a file stream?
This is driving me crazy.

At the end of Main1, sString2 is the second line of the file, as if the
Seek never worked.
Shouldn't sString1 and sString2 each contain the first line of the file?

To fix this (as in Main2), I need to create a new reader. Is this
documented behavior, or is this a bug??

Does it have to be one or the other? :)

StreamReader has an internal buffer of chars which it fills during the first
call to ReadLine(). That buffer is probably large enough to hold the first
two lines. So when you issue the second ReadLine() you get the second line.
At some point StreamReader will read more bytes from the underlying stream
and decode them into its char buffer. Only then will it re-read the first
line.

Lots of the System.IO reader writer classes employ buffering, making
manipulating the underlying streams tricky.

David
 
J

Joan Reddy

I have to create a new stream reader every time I move backwards in the
file. This seems strange to me, but if it is the only way it works, then
I'll do it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top