Tôi gặp sự cố trong khi gửi nhiều tệp đính kèm trong chương trình của mình.Nhiều tệp đính kèm trong C#
Tôi không gặp bất kỳ sự cố nào trước khi tôi cố thêm nhiều tệp đính kèm. Vì vậy, tôi đã thay đổi mã một chút và nó ngừng hoạt động.
Tạo tệp đính kèm: Không thêm tất cả mã để làm cho mã dễ xem hơn.
Attachment attachment = getAttachment(bodyFile, "Formulier" + counter + ".doc");
attachments.Add(attachment);
//attachment.Dispose();
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
email.Attachments.Add(attachment);
}
}
Nhận đính kèm
private Attachment getAttachment(string bodyFile, string title)
{
return createDocument(bodyFile, title);
}
Tạo tập tin
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);
}
Các lỗi tôi nhận được trong logger tôi
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
EDIT
Tôi đã thoát khỏi những phương pháp .Dispose và thay đổi var fstemp = new FileStream(newPath ...
Bây giờ tôi có thể gửi nhiều file đính kèm. Nhưng bây giờ họ ngẫu nhiên đưa ra một lỗi hay không. 4 trong số 5 lần nó hoạt động. Lần thứ tư nó lại đưa ra một lỗi nữa là nó không thể mở tập tin. Lần thứ 5 nó lại hoạt động một cách kỳ diệu.
EDIT: Giải pháp
tôi đã sử dụng một khối sử dụng kết hợp với hai câu trả lời. Và điều đó đã hiệu quả. Tnx đến @HatSoft và @Aghilas Yakoub
Bây giờ tôi nhận được lỗi này khi tôi thử những gì bạn đã nói System.Net.Mail.SmtpException: Không gửi được thư. ---> System.ObjectDisposedException: Không thể truy cập tệp đã đóng. tại System.IO .__ Error.FileNotOpen() – Sllix
Tôi nghĩ rằng điều này đã khắc phục được sự cố. Nhưng đôi khi tôi nhận được một lỗi ngẫu nhiên. Nhưng nó hoạt động tôi đoán. Cảm ơn bạn. – Sllix
Tôi hy vọng tôi có thể tìm thấy vấn đề mới rất nhanh :) – Sllix