本文介绍了将一个内存流对象序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,我正在使用XmlTextWriter将MemoryStream对象转换为字符串.但是我不知道是否有更快的方法将内存流序列化为字符串.
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.
我遵循此处给出的序列化代码- http://www.eggheadcafe .com/articles/system.xml.xmlserialization.asp
I follow the code given here for serialization - 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 [])构造函数.
MSDN报价:
您必须使用此构造函数,并依次设置publiclyVisible = true
使用GetBuffer
You must use this constructor and set publiclyVisible = true
in order to use GetBuffer
这篇关于将一个内存流对象序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!