Search code examples
c#filestreamreadline

FileStream position is off after calling ReadLine() from C#


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. And yes, the file has more than one line :-)

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.

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?


Solution

  • If you need to read lines, and you need to go back to previous chunks, why not store the lines you read in a List? That should be easy enough.

    You should not depend on calculating a length in bytes based on the length of the string - for the reasons you mention yourself: Multibyte characters, newline characters, etc.