7

How to take a stringbuilder and convert it to a stream?

SO my stringbuilder has to be converted into a :

StreamReader stream = ????

Update

I tried using a stringreader like:

StringReader sr = new StringReader(sb.ToString());
StreamReader stream = new StreamReader(sr);

but that doesn't work?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

9

Use ToString to convert the StringBuilder into a String, and use a StringReader to wrap the String as a Stream.

Andy Jacobs
  • 933
  • 3
  • 10
  • 18
  • 1
    but a StreamReader doesn't take a StringReader? – Blankman Feb 24 '10 at 22:29
  • 6
    If you have any control over it, have the function accept a TextReader (instead of StreamReader), which is the base class for both. Otherwise, you may have to use the code Qua posted. – Andy Jacobs Feb 25 '10 at 00:57
7

If using a StreamReader is a requirement then convert the string to a memory stream and then create a new StreamReader using that object:

StreamReader reader= new StreamReader(
                new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())));
Kasper Holdum
  • 12,993
  • 6
  • 45
  • 74
  • 3
    This will result in two unnecessary allocations and copies of the data being made in memory (one by `sb.ToString()` another by `GetBytes()`). A better approach would be to subclass `TextReader` and implement it by reading directly from the `StringBuilder` instance. – Dai Sep 07 '18 at 04:56