簡體   English   中英

與.Net Mail附件一起使用時,處置MemoryStream

[英]Dispose MemoryStream when using with .Net Mail Attachment

我正在使用MemoryStream從存儲在數據庫中的二進制文件中添加附件。 我的問題是我想正確處理MemoryStream。 使用“ using”語句很容易做到這一點,但是當我有多個附件時,我不知道如何正確處理多個MemoryStreams。

有沒有很好的方法來遍歷和附加文件,但是同時正確處理了我要附加的MemoryStreams? 當我嘗試在使用smtp之前刷新/關閉時,通過錯誤發送它,指出流已經關閉。

任何建議,將不勝感激。

我知道這是舊的文章,但事實證明,處置MailMessage或只是封閉其內部using的語句是不夠的時候MailMessage配置所有AttachmentCollection也被設置,當Attachment被布置, Stream還布置。 查看ReferenceSource以獲得完整的代碼。

using(MailMessage mail = new MailMessage())
{
   // Add attachments without worring about disposing them
}

您可以迭代MemoryStream並將其處置。 將處置代碼放入finally塊等於using語句。

var list = new List<MemoryStream>(){new MemoryStream(), new MemoryStream()};

try
{
    //....
}
finally
{
    foreach (var x in list)
    {
        x.Dispose();
    }
}

using語句確保即使在調用對象的方法時發生異常,也將調用Dispose。 通過將對象放在try塊中,然后在finally塊中調用Dispose,可以達到相同的結果。 實際上,這就是編譯器翻譯using語句的方式。

MSDN

using (var ms1 = new MemoryStream())
  using (var ms2 = new MemoryStream())
  {
    ...
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM