Quick way to get the contents of a MemoryStream as an ASCII string

anon355079 picture anon355079 · Aug 22, 2010 · Viewed 14.9k times · Source

I have a JSON string in a MemoryStream. I am using the following code to get it out as an ASCII string:

MemoryStream memstream = new MemoryStream(); 
/* Write a JSON string to memstream here */

byte[] jsonBytes = new byte[memstream.Length];
memstream.Read(jsonBytes, 0, (int)memstream.Length);

string jsonString = Encoding.ASCII.GetString(jsonBytes);

What is a shorter/shortest way to do this?

Answer

Darin Dimitrov picture Darin Dimitrov · Aug 22, 2010

You could use the ToArray method:

using (var stream = new MemoryStream())
{
    /* Write a JSON string to stream here */

    string jsonString = System.Text.Encoding.ASCII.GetString(stream.ToArray());
}