Sll*_*lix 5 c# email-attachments asp.net-mvc-3
我在程序中发送多个附件时遇到问题.
在我尝试添加多个附件之前,我没有遇到任何问题.所以我改变了代码,它停止了工作.
创建附件: 未添加所有代码以使其更易于查看.
Attachment attachment = getAttachment(bodyFile, "Formulier" + counter + ".doc");
attachments.Add(attachment);
//attachment.Dispose();
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
email.Attachments.Add(attachment);
}
}
Run Code Online (Sandbox Code Playgroud)
得到附件
private Attachment getAttachment(string bodyFile, string title)
{
return createDocument(bodyFile, title);
}
Run Code Online (Sandbox Code Playgroud)
创建文件
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);
}
Run Code Online (Sandbox Code Playgroud)
我在记录器中得到的错误
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
Run Code Online (Sandbox Code Playgroud)
编辑
我摆脱了.Dispose方法并更改了var fstemp = new FileStream(newPath ...
现在我可以发送多个附件.但现在他们随机给出错误.5次中有4次有效.第四次再次出现错误,无法打开文件.第五次它再次神奇地起作用.
编辑:解决方案
我使用了一个使用块和两个答案.这很有效.Tnx到@HatSoft和@Aghilas Yakoub
尝试使用以下几行(在您的CreateDocument方法中):
var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read);
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet);
Run Code Online (Sandbox Code Playgroud)