我有字节数组,它本质上是从数据库检索的编码的.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; }
解决方法
附件中有一个
overload of the constructor需要流.您可以通过使用byte []构建一个
MemoryStream来直接传入文件:
MemoryStream stream = new MemoryStream(docFile); Attachment attachment = new Attachment(stream,"document.docx");
第二个参数是文件的名称,从中将推断mime类型.一旦你完成它,请记住在MemoryStream上调用Dispose()
.