Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a String as a Stream in .Net?

Tags:

.net

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?

like image 713
JoshL Avatar asked Oct 02 '08 16:10

JoshL


2 Answers

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();
}
like image 110
Bryant Avatar answered Nov 17 '22 21:11

Bryant


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();
like image 43
Wolfwyrd Avatar answered Nov 17 '22 19:11

Wolfwyrd