2007-12-23

System.IO.StreamReader + complex file processing = Headaches (Part 2)

Yes I know, and I'm terribly sorry that I've took so long to write the continuation of that blog-post. Nevertheless, here it is.

But at first I'd like to sum up the results of the last post:

  • StreamReader is not the right choice for this task.
  • Seeking does not work.
  • The index is completely useless and contains wrong data.
However the good News is that a small and clean facade1 pattern can fix all of this. The Facade can be a simple as this:
class FacadeReader

fields:
An internal position marker, as well as a real FileStream and
StreamReader.

Method ReadLine:
Read the next Line from the StreamReader and then add the
byte-count of the new line + the line feed character(s) to the
internal position marker

Method Seek(position):
Seek on the underlying stream, call
StreamReader.DiscardBufferedData() and last but not least store
the given position at this.position.
That few lines would be enough to make the application run. It is fairly fast and has the big advantage that it's simple to implement (no need to cope with all the low level stuff). Amazing, isn't it?

Oh, I almost forgot: Happy Christmas everybody! :-)

1 Or is this a decorator, am unsure about this.

3 comments:

Amber said...

I'd call this a decorator myself. If you already have other implementations of an existing interface for 'seekable reader' and want to pass this new class as one, it might actually better be named an 'adaptor'.

Anonymous said...

The problem here is to figure out if the line that you just read ends with a \n or with a \r\n or with a \r

Valentin said...

That's true but it can be easily figured out either by defining a standard line-terminator or by probing for the line terminator present in this file.