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.! 🙂

 

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in ASP.NET, CodeProject, General and tagged , , , , , , , , , . Bookmark the permalink.

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

  1. Michael Freidgeim says:

    Stream doesn’t have ReadToEnd() ,
    You need
    ms.Position = 0;
    var sr = new StreamReader(ms);
    var myStr = sr.ReadToEnd();
    See http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from-a-memorystream

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s