Tengo problemas al enviar varios archivos adjuntos en mi programa.Varios archivos adjuntos en C#
No tuve ningún problema antes de intentar agregar varios archivos adjuntos. Así que cambié al código un poco y dejó de funcionar.
Crear archivo adjunto: No agregué todos los códigos para hacerlo más visible.
Attachment attachment = getAttachment(bodyFile, "Formulier" + counter + ".doc");
attachments.Add(attachment);
//attachment.Dispose();
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
email.Attachments.Add(attachment);
}
}
Get Adjunto
private Attachment getAttachment(string bodyFile, string title)
{
return createDocument(bodyFile, title);
}
archivo
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);
}
Creación El error que consigo en mi registrador
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
EDITAR
que se deshizo del método .Dispose y cambiaron var fstemp = new FileStream(newPath ...
Ahora puedo enviar varios archivos adjuntos. Pero ahora dan un error al azar o no. 4 de cada 5 veces funciona. La cuarta vez da un error nuevamente que no puede abrir el archivo. La quinta vez mágicamente funciona de nuevo.
EDIT: Solución
que utiliza un bloque de usar en combinación con dos respuestas. Y eso funcionó. Tnx a @HatSoft y @Aghilas Yakoub
Ahora recibo este error cuando intenté con lo que dijiste System.Net.Mail.SmtpException: Error al enviar el correo. ---> System.ObjectDisposedException: no se puede acceder a un archivo cerrado. en System.IO .__ Error.FileNotOpen() – Sllix
Creo que esto solucionó el problema. Pero a veces recibo un error aleatorio. Pero funciona, supongo. Gracias. – Sllix
Espero que pueda encontrar el nuevo problema muy rápido :) – Sllix