I have a method that takes either a StringReader instance (reading from the clipboard) or a StreamReader instance (reading from a file) and, at present, casts either one as a TextReader instance.
I need it to ‘pre-read’ some of the source input, then reset the cursor back to the start. I do not necessarily have the original filename. How to I do this?
There is mention of the Seek method of System.IO.Stream but this is not implemented in TextReader, although it is in StreamReader through the Basestream property. However StringReader does not have a BaseStream property
It depends on the
TextReader. If it’s aStreamReader, you can use:(Assuming the underlying stream is seekable, of course.)
Other implementations of
TextReadermay not have a concept of “rewinding”, in the same way thatIEnumerable<T>doesn’t. In many ways you can think ofTextReaderas a glorifiedIEnumerable<char>. It has methods to read whole chunks of data at a time, read lines etc, but it’s fundamentally a “forward reading” type.EDIT: I don’t believe
StringReadersupports any sort of rewinding – you’d be better off recreating theStringReaderfrom the original string, if you can. If that’s not feasible, you could always create your ownTextReaderclass which proxies all the “normal” calls to anotherStringReader, but recreates that proxy instance when it needs to.