加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将memorystream对象序列化为字符串

发布时间:2020-12-15 17:39:01 所属栏目:百科 来源:网络整理
导读:现在我使用XmlTextWriter将一个MemoryStream对象转换成字符串.但是我不知道是否有更快的方法来将memorystream序列化为字符串. 我按照这里给出的代码序列化 – http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp 编辑 流到字符串 ms.Posi
现在我使用XmlTextWriter将一个MemoryStream对象转换成字符串.但是我不知道是否有更快的方法来将memorystream序列化为字符串.

我按照这里给出的代码序列化 – http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp

编辑

流到字符串

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

字符串流

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

解决方法

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

当您使用MemoryStream(byte[])构造函数时,您不能使用GetBuffer.

MSDN报价:

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

您必须使用此constructor并设置ublicVisible= true才能使用GetBuffer

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读