微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

现在我使用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

原文地址:https://www.jb51.cc/csharp/96569.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐