I have 3 TextReaders -- a combination of StreamReaders and StringReaders. Conceptually, the concatenation of them is a single text document.
I want to call a method (not under my control) that takes a single TextReader. Is there any built-in or easy way to make a concatenating TextReader from multiple TextReaders?
(I could write my own TextReader subclass, but it looks like a fair amount of work. In that case, I'd just write them all out to a temp file and then open it with a single StreamReader.)
Is there an easy solution to this that I'm missing?
I just threw this together, so it's not super-robust (no error handling, etc) but the basic test case works.
It works by creating an extension method for
TextReader
's which take a second, and returns a new TextReader class which internally callsRead()
on the first until it runs out, and then starts callingRead()
on the second. You can chain this indefinitely.To provide a complete implementation of
TextReader
you only need to implementRead()
,Peek()
,Close()
andDispose()
. All the other methods rely on specific implementationRead()
to work. So creating your ownTextReader
really isn't so bad, as you can see below.This also alleviates any performance concerns since we are simply wrapping the existing TextReaders and not actually invoking them to perform the concatenation.