Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access TextReader as a Stream

Tags:

c#

.net

stream

I would like to have similar functionality for a TextReader that a Stream has. Specifically the ability to set position in the stream. Is there any way to change a TextReader into a stream?

I would like to accept a TextReader but access it like a Stream.

like image 402
galford13x Avatar asked Oct 17 '25 17:10

galford13x


2 Answers

You can obtain a Stream through the use of the StreamReader class. StreamReader is a subclass of TextReader so you can easily access its stream property by doing the following:

    TextReader reader = File.OpenText("C:\\todo.txt");
    Stream stream = ((StreamReader)reader).BaseStream;

Depending on what you need to do, you may also be able to just use the StreamReader class.

Source: http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx

Hope this helps!

like image 59
Andrew White Avatar answered Oct 20 '25 07:10

Andrew White


You can't do this in the general case. Not all TextReader instances are based on streams.

Also, a TextReader is based on lines of text, where the line terminators may not be the sort that you can back up over.

like image 29
John Saunders Avatar answered Oct 20 '25 07:10

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!