2010-07-07 86 views
10

我有一個字節數組,它基本上是從數據庫中檢索到的編碼.docx。我嘗試將此字節[]轉換爲原始文件,並將其作爲郵件附件,而不必先將其作爲文件存儲在磁盤上。 這是怎麼回事?如何將字節數組轉換爲郵件附件

public MailMessage ComposeMail(string mailFrom, string mailTo, string copyTo, byte[] docFile) 
{ 
    var mail = new MailMessage(); 

    mail.From = new MailAddress(mailFrom); 

    mail.To.Add(new MailAddress(mailTo)); 
    mail.Body = "mail with attachment"; 

    System.Net.Mail.Attachment attachment; 

    //Attach the byte array as .docx file without having to store it first as a file on disk? 
    attachment = new System.Net.Mail.Attachment("docFile"); 
    mail.Attachments.Add(attachment); 

    return mail; 
} 

回答

16

有一個overload of the constructorAttachment需要一個流。可以直接通過使用byte[]構建MemoryStream文件中傳遞:

MemoryStream stream = new MemoryStream(docFile); 
Attachment attachment = new Attachment(stream, "document.docx"); 

第二個參數是該文件,從該mime類型將被推斷的名稱。一旦完成,請記得在MemoryStream上致電Dispose()

相關問題