2009-08-25 77 views
1

對於.Net MemoryStream對象實例,是否需要在使用後明確關閉它?或者不需要關閉它?哪些是最佳做法?.Net MemoryStream關閉問題

我使用的是VSTS2008 + .Net 3.5 + C#。

回答

9

更好的辦法是使用Using

using (MemoryStream ms = /*get it using your favorite ctor*/) 
{ 
    // use it here 

    // and now flush and copy to a file stream (for example) 
    ws.Flush(); 
    byte[] buffer = ws.ToArray(); 
    using (Stream stream = new FileStream("fileName", FileMode.Create)) 
     stream.Write(buffer, 0, buffer.Length); 
} 

小提醒 - 如果你打算給它的所有寫入到另一個流末,不要」 t忘記Flush()(並且不要讓馬桶座位離開)。

我在ms周圍使用StreamWriter,將文本數據寫入內存,並最終將所有內容放在光盤上。 (如果你願意的話,我也可以把這個例子改成這個例子)

+0

「最後把它寫入另一個流中」 - 你能給我看一個樣品嗎?你什麼意思是「最後流入另一個流」? – George2 2009-08-25 04:38:56

+1

爲什麼要刷新內存流?此方法的評論是:「重寫Flush以便不執行任何操作。」 – 2010-01-22 12:18:26

+0

我想我從'StreamStreamer'的'MemoryStream'的用法複製了代碼,並且我正在刷新'StreamWriter'實例,以確保寫入它的所有文本在讀取之前都在MemoryStream的「內部」陣列。 我記得起初沒有刷新,並得到了不包含所有預期數據的文件。 – 2010-01-24 14:49:28