JoshL
JoshL

Reputation: 10988

How do I use a String as a Stream in .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?

Upvotes: 6

Views: 532

Answers (5)

Bryant
Bryant

Reputation: 8670

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();
}

Upvotes: 7

itsmatt
itsmatt

Reputation: 31406

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.

Upvotes: 2

Tom
Tom

Reputation: 1611

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);

Upvotes: 0

Wolfwyrd
Wolfwyrd

Reputation: 15916

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();

Upvotes: 5

user8032
user8032

Reputation: 1221

Look up MemoryStream class

Upvotes: 2

Related Questions