3

I have a TextReader which has been created by a black-boxed system so I don't have any information about the source file from which it was created.

I need to pass this TextReader back into the black-boxed system inside an object which I am creating in my application.

However, I need to get some information from the TextReader to assist with the creation of my object.

I understand that you can't "rewind" a TextReader but is there a way to duplicate it so that I can read and discard a temporary copy without advancing the source TextReader at all?

I have had a look at this SO thread but I'm not sure if that relates to my requirement.

If it does, could someone please elaborate so I can understand?

Thanks in advance.

Community
  • 1
  • 1
Ste
  • 1,136
  • 2
  • 10
  • 30
  • Reading means advancing the text reader. If you have a temporary copy, how should the copy get the data from the source text reader without reading from the source text reader? It cannot, hence I doubt this is possible. – O. R. Mapper Jun 14 '12 at 15:56
  • I guess I was wondering if it could be duplicated in memory under the hood rather than using one of the Read methods. – Ste Jun 14 '12 at 16:11
  • It usually cannot. Imagine a reader not like an object that contains all the data and outputs it when `Read` is invoked. Rather, a reader is an object that knows where to find the data and fetches it from there upon invocation of `Read`. Likewise, the current "position" is not an internal property of the reader, but possibly (depending on the type of the reader) something inherent to the data source. – O. R. Mapper Jun 14 '12 at 16:19

1 Answers1

3

Well sort of hack, but you can do like this, ReadToEnd the entire text in a string, do what you want, and pass back a new StringReader created with the string you read before. I expect the blackboxed system will work like a charm.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115