2011-05-28 39 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#可能適用

相關問題