StreamReader problems with BaseStream Position

G

Guest

Hi,

I'm creating a class to read some text datafiles.

These files start with a header with variable length, followed by a section
with data values (numbers in separate lines) also with variable length. The
data section must be read sequentialy, so my approch to this is:

-Read the header (line by line) until find the header's end.
-Store the Position of the BaseStream property of the StreamReader
-Read the data section (also line by line)

I need to store the stream position before start reading the data section,
to be able to re-read the data without having to parse the header again.

The problem is that the StreamReader buffers data, so the value returned in
BaseStream.Position property is always ahead of the actual processed line.

I understand that we need to call DiscardBufferedData after seeking in the
base stream, so we start to read in the right position.

But how can I know the exact position, discarding the buffered data that was
not returned in the ReadLine method?

Any other way to make this?

Thanks!
 
J

Jon Skeet [C# MVP]

ferreira said:
I'm creating a class to read some text datafiles.

These files start with a header with variable length, followed by a section
with data values (numbers in separate lines) also with variable length. The
data section must be read sequentialy, so my approch to this is:

-Read the header (line by line) until find the header's end.
-Store the Position of the BaseStream property of the StreamReader
-Read the data section (also line by line)

I need to store the stream position before start reading the data section,
to be able to re-read the data without having to parse the header again.

The problem is that the StreamReader buffers data, so the value returned in
BaseStream.Position property is always ahead of the actual processed line.

I understand that we need to call DiscardBufferedData after seeking in the
base stream, so we start to read in the right position.

But how can I know the exact position, discarding the buffered data that was
not returned in the ReadLine method?

I'm afraid you can't, as far as I know. If the file is encoded in a
text encoding which is fixed-width, you could keep track of how much
text has been read and multiply that by the width, but that's the only
solution I know of :(
 
G

Guest

Hi,

Thanks for your reply.

The files are ASCII encoded, so the method you pointed works and is also
very simple :)

Thanks for the suggestion!

Pedro
 

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

Similar Threads


Top