Serializing a memorystream object to string

末鹿安然 提交于 2019-12-01 14:15:13

问题


Right now I'm using XmlTextWriter to convert a MemoryStream object into string. But I wan't to know whether there is a faster method to serialize a memorystream to string.

I follow the code given here for serialization - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp

Edited

Stream to String

ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
    string content = sr.ReadToEnd();
    SaveInDB(ms);
}

String to Stream

string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray); 
byte[] outBuf = ms.GetBuffer(); //error here

回答1:


using(MemoryStream stream = new MemoryStream()) {
   stream.Position = 0;
   var sr = new StreamReader(stream);
   string myStr = sr.ReadToEnd();
}

You cant use GetBuffer when you use MemoryStream(byte[]) constructor.

MSDN quote:

This constructor does not expose the underlying stream. GetBuffer throws UnauthorizedAccessException.

You must use this constructor and set publiclyVisible = true in order to use GetBuffer




回答2:


In VB.net i used this

Dim TempText = System.Text.Encoding.UTF8.GetString(TempMemoryStream.ToArray())

in C# may apply



来源:https://stackoverflow.com/questions/6161453/serializing-a-memorystream-object-to-string

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