2011-05-28 87 views
10

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

可能DUPLIC吃了[如何从一个MemoryStream字符串?](http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from-a-memorystream) – 2016-03-23 12:26:21

回答

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

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

MSDN报价:

此构造不公开 底层流。 GetBuffer抛出 UnauthorizedAccessException。

必须使用此constructor并为了使用的GetBuffer

+0

恐怕这不会给写字符串。在我尝试将字符串转换回内存流后,它抛出错误消息“MemoryStream的内部缓冲区无法访问”。同时做memorystream.GetBuffer()。 – NLV 2011-05-28 12:50:47

+0

你能显示你的代码片段吗? – Stecya 2011-05-28 13:06:16

+0

已更新帖子中的代码。原始的内存流大约95000字节。但是,在我将字符串转换回流后,我只获得了1900个字节。 – NLV 2011-05-28 13:21:29

0

在VB.net我用这个

昏暗TempText = System.Text.Encoding.UTF8.GetString设置publiclyVisible = true(TempMemoryStream .ToArray())

在C#可能适用

相关问题