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?
+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
2008-10-02 16:09:53
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
2008-10-02 16:14:03
+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
2008-10-02 16:11:17
Might want to mention that you'll have to rewind the stream before using it to read from it. :)
Nick Johnson
2008-10-02 16:14:34
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
2008-10-02 16:13:26
Or you could just construct the MemoryStream from the bytes1[] array.
Nick Johnson
2008-10-02 16:19:07
+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
2008-10-02 16:31:22
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
2008-10-02 16:38:37
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
2008-10-02 16:42:15