c# - 将内存流对象序列化为字符串

标签 c# xml-serialization memorystream

现在我正在使用 XmlTextWriter 将 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并设置 publiclyVisible = true 以使用 GetBuffer

关于c# - 将内存流对象序列化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6161453/

相关文章:

c# - 如何序列化/反序列化生成的 WCF 代理代码?

delphi - 在 Delphi 10.2 中写入 MemoryStream 有何变化?

c# - 我正在尝试用 C# 为静态方法编写单元测试

c# - 多个开发人员同时 checkin 迁移时的 EF 迁移

c# - 为什么我的时间增加了两个小时

c# - 图像 split 成 9 block

C# XML 序列化 - 前导问号

c# - 将类转换为 XML 到字符串

c# - 使用 ITextSharp 从内存流附加 PDF 文件时遇到问题

c# - 从 MemoryStream 反序列化对象时出错