tags:

views:

274

answers:

5

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?

+2  A: 

Look up MemoryStream class

+5  A: 

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();
Wolfwyrd
A StringWriter is a type of TextWriter, not a type of Stream, so it can't be passed to a method that expects a Stream.
Nick Johnson
+7  A: 

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();
}
Bryant
Might want to mention that you'll have to rewind the stream before using it to read from it. :)
Nick Johnson
A: 

you can do something like:

string s = "Wahoo!";
int n = 452;

using( Stream stream = new MemoryStream() ) {
  // Write to the stream

  byte[] bytes1 = UnicodeEncoding.Unicode.GetBytes(s);
  byte[] bytes2 = BitConverter.GetBytes(n);
  stream.Write(bytes1, 0, bytes1.Length);
  stream.Write(bytes2, 0, bytes2.Length);
Tom
Or you could just construct the MemoryStream from the bytes1[] array.
Nick Johnson
+2  A: 
MemoryStream ms = new MemoryStream();
YourFunc(ms);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string mystring = sr.ReadToEnd();

is one way to do it.

itsmatt
Hmm... didn't see Bryant's response earlier - essentially the same thing. Oh well. His will work if you add the Seek call to it.
itsmatt
This code actually works. It would be great to merge this with Bryant's better-formatted response, but I don't have the reputation to do that yet...
JoshL