Converting a string to stream and a stream to string in C#

Hi,

Today I’ll just put a small post about converting a string to stream and a stream to string in C#. These conversions are pretty much simple but they did cause some trouble to me. So thought I would just put it in my blog for easy reference later on.

 

Converting a string to stream in C#:

There are two steps in this process.

  1. Convert your string to byte array
  2. Read that byte array into a stream

 

Both the steps can be showing with the following code snippet:

 

string myString = “Amogh Natu”;

byte[] arrayOfMyString = Encoding.UTF8.GetBytes(myString”);

MemoryStream stream = new MemoryStream(arrayOfMyString);

 

The above variable named “stream” would have the stream notation of the string.

 

Converting a stream to string in C#:

 

This conversion is pretty much straight forward. The “ReadToEnd()” method does all the work for us by converting the stream into a string.

 

//Stream inputStream

string myString = stream.ReadToEnd();

 

Now “myString” would hold the string representation of the stream.

 

Hope this helps.! 🙂

Â