C# FileStream position is off after calling ReadLine()

Posted by Cristi Diaconescu on Stack Overflow See other posts from Stack Overflow or by Cristi Diaconescu
Published on 2010-05-28T16:40:47Z Indexed on 2010/05/28 16:41 UTC
Read the original article Hit count: 522

Filed under:
|
|
|

I'm trying to read a (small-ish) file in chunks of a few lines at a time, and I need to return to the beginning of particular chunks.

The problem is, after the very first call to

streamReader.ReadLine();

the streamReader.BaseStream.Position property is set to the end of the file! Now I assume some caching is done in the backstage, but I was expecting this property to reflect the number of bytes that I used from that file.

For instance, calling ReadLine() again will (naturally) return the next line in the file, which does not start at the position previously reported by streamReader.BaseStream.Position.

My question is, how can I find the actual position where the 1st line ends, so I can return there later?

I can only think of manually doing the bookkeeping, by adding the lengths of the strings returned by ReadLine(), but even here there are a couple of caveats:

  • ReadLine() strips the new-line character(s) which may have a variable length (is is '\n' ? is it "\r\n" ? etc)
  • I'm not sure if this would work ok with variable-length characters

...so right now it seems like my only option is to rethink how I parse the file, so I don't have to rewind.

If it helps, I open my file like this:

using (var reader = new StreamReader(
        new FileStream(m_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{...}

Any suggestions?

© Stack Overflow or respective owner

Related posts about c#

Related posts about filestream