I need to call a method that accepts a stream argument. The method loads text into the stream, which would normally be a file. I'd like to simply populate a string with the contents of the stream, instead of writing it to a file. How do I do this?
Use a MemoryStream with a StreamReader. Something like:
using (MemoryStream ms = new MemoryStream())
using (StreamReader sr = new StreamReader(ms))
{
// pass the memory stream to method
ms.Seek(0, SeekOrigin.Begin); // added from itsmatt
string s = sr.ReadToEnd();
}
Use the StringWriter to act as a stream onto a string:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
CallYourMethodWhichWritesToYourStream(sw);
return sb.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With