Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get System.IO.Stream from a String Object

Tags:

string

c#

I have string object. I need to pass this data to another object of type XYZ. But this object of type XYZ is taking only System.IO.Stream. So how to convert the string data into a stream so that object of XYZ type can use this string data?

like image 647
dotcoder Avatar asked Sep 28 '10 12:09

dotcoder


2 Answers

You'll have to pick a text encoding to use to translate the string into a byte array, then use a MemoryStream to call your function. For example:

using(System.IO.MemoryStream ms = new System.IO.MemoryStream(
     System.Text.Encoding.UTF16.GetBytes(yourString)))
{
    XYZ(ms);
}

You can alter UTF16 to be whatever encoding you'd like to use to pass the string.

like image 158
Adam Robinson Avatar answered Nov 03 '22 00:11

Adam Robinson


Assuming you want the string's stream encoded in UTF8:

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( "the string"));

Depending on what you really want to do, you might be better served using the StringReader class. It's not an IO.Stream, but it makes for easy text-oriented reading of a string.

like image 43
Thakur Avatar answered Nov 03 '22 00:11

Thakur