2012-07-04 46 views
5

我在我的程序中發送多個附件時遇到了問題。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

回答

2

與這些線(在你的CreateDocument法)試試:

var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read); 
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet); 
+0

現在我收到這個錯誤,當我試着你說的 System.Net.Mail。SmtpException: 發送郵件失敗。 ---> System.ObjectDisposedException:無法訪問已關閉的文件。 在System.IO .__ Error.FileNotOpen() – Sllix

+0

我認爲這解決了這個問題。但有時我會隨機發生一個錯誤。但它的工作我猜。謝謝。 – Sllix

+1

我希望我能很快找到新問題:) – Sllix

0

它看起來像FileStream中的newPath fs = File.Create(newPath);是不正確的,並沒有文件得到創建,看着你的代碼,新路徑將以'文檔'和File.Create文件名以擴展名結束,因此他們不會被附加任何東西。

+0

文件確實已創建。在我的解決方案資源管理器中顯示。 – Sllix

+0

你可以告訴我什麼是在FileStream裏調用FileMode.Open之前在newPath裏面嗎 – HatSoft

+1

看起來FileStream也需要FileAccess來讀取,也請把FileStream放在一個使用塊 – HatSoft

2

什麼是3號線在代碼中做什麼?

attachment.Dispose(); 

它看起來像將它添加到郵件你正在處理該文件。因此可能會在附件完成之前關閉文件。

+0

當我不這樣做,我得到一個錯誤,說:不能訪問一個打開的文件.. – Sllix

+0

謝謝這是一部分的問題。 – Sllix