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

使用MemoryStream(byte [])构造函数时,无法使用GetBuffer。

MSDN报价:

此构造函数不公开基础流。 GetBuffer抛出UnauthorizedAccessException。

您必须使用此构造函数并设置publiclyVisible = true才能使用GetBuffer

在VB.net中我使用了这个

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

在C#中可能适用