c# - c#中的多个附件

标签 c# asp.net-mvc-3 email-attachments

我在程序中发送多个附件时遇到问题。

在尝试添加多个附件之前,我没有遇到任何问题。 所以我更改了一些代码,但它停止工作了。

创建附件: 没有添加所有代码以使其更易于查看。

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/

相关文章:

c# - 调试原始 View 内容

visual-studio-2010 - 将 ASP.NET MVC 3 项目部署到 Windows Server 2003 的最简单方法是什么?

c# - 将 Webforms 站点移植到 MVC 需要多长时间?

python - 如何让 Python AWS Lambda 打开作为电子邮件对象存储在 S3 中的电子邮件

c# - 如何将值添加到 list<valuepair> 对象

c# - 合并相同类型的列表<T>

c# - 根据给定日期计算当前或下一个年度季度的第一个月和当前年度季度的最后一个月

css - 内容未加载?

从 Gmail 回复时,电子邮件签名成为附件

pdf - 将 PDF 读取为 Blob,然后作为附件发送