我在我的程序中發送多個附件時遇到了問題。c中的多個附件#
我在嘗試添加多個附件之前沒有遇到任何問題。 所以我改變了一下代碼,它停止了工作。
創建附件: 未添加所有代碼以使其更易於查看。
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 ...
現在我可以發送多個附件。但現在他們隨機給出了一個錯誤或不。 4次,5次。第四次,它再次發出錯誤,它無法打開文件。第五次它神奇地再次工作。
編輯:解
予組合使用一個使用塊具有兩個解答。這工作。 Tnx to @HatSoft和@Aghilas Yakoub
現在我收到這個錯誤,當我試着你說的 System.Net.Mail。SmtpException: 發送郵件失敗。 ---> System.ObjectDisposedException:無法訪問已關閉的文件。 在System.IO .__ Error.FileNotOpen() – Sllix
我認爲這解決了這個問題。但有時我會隨機發生一個錯誤。但它的工作我猜。謝謝。 – Sllix
我希望我能很快找到新問題:) – Sllix