我在程序中发送多个附件时遇到问题。
在尝试添加多个附件之前,我没有遇到任何问题。 所以我更改了一些代码,但它停止工作了。
创建附件: 没有添加所有代码以使其更易于查看。
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 次,它再次给出无法打开文件的错误。第 5 次它又神奇地起作用了。
编辑:解决方案
我结合使用了一个 using block 和两个答案。这奏效了。 Tnx @HatSoft 和@Aghilas Yakoub
最佳答案
尝试使用这些行(在您的 CreateDocument
方法中):
var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read);
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet);
关于c# - c#中的多个附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330895/