我在程序中发送多个附件时遇到问题。
在尝试添加多个附件之前,我没有任何问题。所以我改变了一点代码,它停止了工作。
创建附件: 未添加所有代码以使其更易于查看。
Attachment attachment = getAttachment(bodyFile, "Formulier" + counter + ".doc");
attachments.Add(attachment);
//attachment.Dispose();
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
email.Attachments.Add(attachment);
}
}
获取附件
private Attachment getAttachment(string bodyFile, string title)
{
return createDocument(bodyFile, title);
}
创建文件
private Attachment createDocument(string bodyFile, string title)
{
string activeDir = HttpContext.Current.Server.MapPath("/Tools");
string newPath = Path.Combine(activeDir, "Documents");
Directory.CreateDirectory(newPath);
newPath = Path.Combine(newPath, title);
FileStream fs = File.Create(newPath);
fs.Close();
File.WriteAllText(newPath, bodyFile);
var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read);
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet);
}
我在记录器中遇到的错误
2012-07-04 15:45:26,149 [19] ERROR Mvc - System.Net.Mail.SmtpException: Failure sending mail. ---> System.ObjectDisposedException: Cannot access a closed file.
at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.Net.Mime.MimePart.Send(BaseWriter writer)
at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ARTex.Tools.Mailer.Send(SmtpClient smtpClient, List`1 receivers, String subject, String body, List`1 attachments, String cc) in C:\Projects\KTN.Web.ARTex\ARTex\ARTex\Tools\Mailer.cs:line 262
编辑
我摆脱了 .Dispose 方法并更改了var fstemp = new FileStream(newPath ...
现在我可以发送多个附件。但是现在他们随机给出错误与否。5 次中有 4 次有效。第 4 次再次出现无法打开文件的错误。第五次它又神奇地起作用了。
编辑:解决方案
我将 using 块与两个答案结合使用。这奏效了。Tnx 到 @HatSoft 和 @Aghilas Yakoub