Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to System.IO.Stream [duplicate]

Tags:

c#

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);
like image 654
xbonez Avatar asked Nov 08 '11 07:11

xbonez


People also ask

Can convert from string to system IO stream?

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

What is System io MemoryStream?

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.

What is the use of MemoryStream in c#?

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.


2 Answers

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();
like image 155
Marco Avatar answered Oct 17 '22 21:10

Marco


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:

  • http://msdn.microsoft.com/en-us/library/ds4kkd55%28v=VS.100%29.aspx
  • http://msdn.microsoft.com/en-us/library/e55f3s5k.aspx
like image 53
Yahia Avatar answered Oct 17 '22 20:10

Yahia