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

試著忘記壹切 提交于 2019-12-12 07:47:18

问题


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?


回答1:


You could use the ToArray method:

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

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



回答2:


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



来源:https://stackoverflow.com/questions/3542237/quick-way-to-get-the-contents-of-a-memorystream-as-an-ascii-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!