开发者

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

开发者 https://www.devze.com 2023-01-13 02:45 出处:网络
I have a JSON string in a MemoryStream. I am using the following code to get it out as an ASCII string:

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?


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


new StreamReader(memstream, Encoding.ASCII).ReadToEnd()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号