title: Capture Stream Output to String
body: <p>I'm calling a library method that writes to a stream. But I want to write to a string. Is this possible? (I do not control the source code of the method I'm calling and so changing that is not an option.)</p>
  
  <p>Experimenting, I tried something like this:</p>
  
  <pre><code>iCalendarSerializer serializer = new iCalendarSerializer();
  MemoryStream stream = new MemoryStream();
  serializer.Serialize(new iCalendar(), stream, System.Text.Encoding.UTF8);
  byte[] buff = new byte[stream.Length];
  stream.Read(buff, 0, (int)stream.Length);
  </code></pre>
  
  <p>But I get an error on the last line that's something about not being able to access a closed stream. Apparently, the Serialize() method closes the stream when it's done.</p>
  
  <p>Are there other options?</p>