sto avendo dei problemi, mentre l'invio di più allegati nel mio programma.più allegati in C#
io non ho avuto alcun problema prima ho cercato di aggiungere più allegati. Così ho cambiato il codice un po 'e ha smesso di funzionare.
Crea attacco: non aggiungere tutto il codice per renderlo più visibile.
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 Allegato
private Attachment getAttachment(string bodyFile, string title)
{
return createDocument(bodyFile, title);
}
Creazione di file
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);
}
L'errore che ottengo nella mia logger
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
mi sono liberato del metodo .Dispose e cambiato var fstemp = new FileStream(newPath ...
Ora posso inviare più allegati. Ma ora danno casualmente un errore o no. 4 volte su 5 funziona. 4a volta dà di nuovo un errore che non può aprire il file. Quinta volta funziona di nuovo magicamente.
EDIT: Soluzione
ho usato un blocco utilizzando in combinazione con due risposte. E quello ha funzionato. Tnx a @HatSoft e @Aghilas Yakoub
Ora ricevo questo errore quando ho provato quello che hai detto System.Net.Mail.SmtpException: Errore nell'invio della posta. ---> System.ObjectDisposedException: impossibile accedere a un file chiuso. a System.IO .__ Error.FileNotOpen() – Sllix
Penso che questo abbia risolto il problema. Ma a volte ottengo un errore casuale. Ma funziona credo. Grazie. – Sllix
Spero di trovare il nuovo problema molto velocemente :) – Sllix