2010-07-07 77 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()

相关问题