Streams and file poistion seeking

N

nevin

(having a nightmare with my news client(s) so apologies if this appears more
than once)
Hi All,

I have a text file of 12k that I read the first 5 lines of with a
StreamReader.ReadLine() in a loop. The streamreader is then passed to
another method to read the last bit of text in the file.
I try something like:
// put the stream position to the end last 200 chars
sr.BaseStream.Seek(-200, SeekOrigin.End);
// read in the last 200 chars
string s = sr.ReadToEnd();

The variable s should be 200 chars long but it's 630.
The data should be the end of the file but it's the 630 chars following the
original 5 LineRead()'s.
The Position of the sr.BaseStream is showing the correct position before the
ReadToEnd().
From the position it is reading from, there is about 11k of text data but it
only reads 630 chars.

So, not only is it not reading from where the Position says it should, it's
not reading to the end of the file either.
Can someone shed some light on this for me please?
Thanks.
 
M

Mohamoss

Hi
the problem seems to be somewhere else in your code " a part that you
didn't mention in your post maybe " . i think so because the logic you
descriped in your post should work fine and give you the result that you
are expecting " the last 200 char of the file " . just to make sure , i did
this sample and tried it , it works fine.............
System.IO.StreamReader st = new StreamReader("c:\\testtxt.txt");
st.BaseStream.Seek(-200,SeekOrigin.End);
int current =(int) st.BaseStream.Position;
string output = st.ReadToEnd();
Console.WriteLine(output);
Console.WriteLine(output.Length);
st.BaseStream.Seek(0, SeekOrigin.End);
Console.WriteLine(st.BaseStream.Position-current);
hope this would help you figure out what is wrong ... if still the problem
persist and you have more detalis please post them and i will try to help
 
J

Jon Skeet [C# MVP]

Mohamoss said:
the problem seems to be somewhere else in your code " a part that you
didn't mention in your post maybe " . i think so because the logic you
descriped in your post should work fine and give you the result that you
are expecting " the last 200 char of the file " .

No, it shouldn't. The reader can buffer information - you need to call
DiscardBufferedData just before or after you seek.
 

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