Advertisement
Advertisement


Convert String to System.IO.Stream


Question

I need to convert a String to System.IO.Stream type to pass to another method.

I tried this unsuccessfully.

Stream stream = new StringReader(contents);
2011/11/08
1
153
11/8/2011 7:13:57 AM

Accepted Answer

Try this:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);

and

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
2011/11/08
339
11/8/2011 7:16:31 AM

To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:

MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );

MSDN references:

2011/11/08

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
2011/11/08

string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
2011/11/08

this is old but for help :

you can also use the stringReader stream

string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
2012/10/18

Source: https://stackoverflow.com/questions/8047064
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]