简体   繁体   English

将内存流 object 序列化为字符串

[英]Serializing a memorystream object to string

Right now I'm using XmlTextWriter to convert a MemoryStream object into string.现在我正在使用 XmlTextWriter 将 MemoryStream object 转换为字符串。 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我按照此处给出的代码进行序列化 - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp

Edited已编辑

Stream to String Stream 转字符串

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

String to Stream字符串到 Stream

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();
}

You cant use GetBuffer when you use MemoryStream(byte[]) constructor.使用MemoryStream(byte[])构造函数时不能使用 GetBuffer。

MSDN quote: MSDN 报价:

This constructor does not expose the underlying stream.此构造函数不公开底层 stream。 GetBuffer throws UnauthorizedAccessException. GetBuffer 抛出 UnauthorizedAccessException。

You must use this constructor and set publiclyVisible = true in order to use GetBuffer您必须使用此构造函数并设置publiclyVisible = true才能使用 GetBuffer

In VB.net i used this在 VB.net 我用这个

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

in C# may apply在 C# 可能适用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM