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);
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 ) );
MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.
The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty.
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();
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With