Read Backwards in a text file

J

JB

I'm trying to read a text file, and store the position of a specified
line, and then later seek back to that line and start reading again.

I'm using simple code like the following:

StreaReader sr = new StreamReader("test.txt");
String s = "";
while (S != null)
{
S = sr.ReadLine()
//process line
}


sr.BaseStream.Position always returns the same value (1024) so isn't
much use in this regard.

I can track the line position manually, but then i cant Seek back to
the start of said line.
Or Can I?

Cheers guys,
 
P

Peter Duniho

[...]
sr.BaseStream.Position always returns the same value (1024) so isn't
much use in this regard.

I can track the line position manually, but then i cant Seek back to
the start of said line.
Or Can I?

The BaseStream and the StreamReader are not always at the same position,
because the StreamReader buffers data from the BaseStream. That's why the
BaseStream.Position is returning 1024; the StreamReader has already read
1024 bytes from the BaseStream at the point you check the property's value.

You can go back to a specific position by setting the Position property of
the BaseStream, and then calling DiscardBufferedData() on the
StreamReader. This will force the StreamReader to sync back up with your
new position in the BaseStream.

So, as long as you keep track of the actual position to which you want to
seek somehow, you can go back to that position any time you like.

Keep in mind that this is only possible, of course, for seekable streams.
Not all streams support seeking.

Pete
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

JB said:
I'm trying to read a text file, and store the position of a specified
line, and then later seek back to that line and start reading again.

I'm using simple code like the following:

StreaReader sr = new StreamReader("test.txt");
String s = "";
while (S != null)
{
S = sr.ReadLine()
//process line
}


sr.BaseStream.Position always returns the same value (1024) so isn't
much use in this regard.

I can track the line position manually, but then i cant Seek back to
the start of said line.
Or Can I?

Cheers guys,

The problem with moving the file pointer in a text file is that you want
to move to a specific character in the file, but the file pointer
doesn't know about characters, it only knows about bytes.

You could create your own line based stream reader that uses the fact
that the line break (cr+lf) is of a known size regardless of the
encoding used. You could read the bytes from the stream until you
encounter a line break, and then decode the bytes in the line. That way
you could get the file pointer location of a line.
 

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