Streams seeking and reading not working

N

Nevin

Hello,
I have a text file of about 12k which I read the first 5 lines using a
StreamReader.ReadLine() in a loop, all ok.
The reader is passed to another function to read the last piece of text in
the file and this is where it's going wrong. I'm doing something like:
sr.BaseStream.Seek(-200, SeekOrigin.End);
// get the remains of the file
string n = sr.ReadToEnd();

But while I see the base streams position moving exactly where it should,
the subsequent ReadToEnd() reads from where the previous methods
ReadLine()'s left off.
Not only that but the ReadToEnd() should only read 200 chars as the
position should be 200 from the end but it reads in 630 chars from 5 lines
into the file (which isn't to then end of the file either).
This is mega simple stuff and I'm not sure why it's not working.
 
N

Nicholas Paldino [.NET/C# MVP]

Nevin,

This was answered in a previous post. When you change the position of
the underlying Stream without using StreamReader, you must call
DiscardBufferedData in order to reset the buffer that the StreamReader uses.
 
J

Jon Skeet [C# MVP]

Nevin said:
I have a text file of about 12k which I read the first 5 lines using a

<snip>

Please see the responses to your post from half an hour earlier.
 

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