[英]Multiple attachments in 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 ...
現在我可以發送多個附件。但現在他們隨機發出錯誤或者沒有錯誤.5次中有4次是有效的。第4次它給出了一個錯誤,它無法打開文件。第五次它神奇地再次工作。
編輯:解決方案
我使用了一個使用塊和兩個答案。 這很有效。 Tnx到@HatSoft和@Aghilas Yakoub
嘗試使用這些行(在您的CreateDocument
方法中):
var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read);
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet);
第3行在代碼中做什么?
attachment.Dispose();
看起來在將其添加到Mail之前,您正在處理該文件。 因此,在附件完成之前,文件可能會被關閉。
它看起來像FileStream中的newPath fs = File.Create(newPath); 是不正確的,沒有文件被創建,看着你的代碼newPath將以'Documents'結束,File.Create文件名帶有擴展名,因此它們不會附加任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.