Multiple Attachments in C #

I am having trouble sending multiple attachments to my program.

I had no problems before I tried to add some attachments. So I changed the code a bit and stopped working.

Create an attachment: Did not add all the code to make it more convenient to view.

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 an attachment

private Attachment getAttachment(string bodyFile, string title)
{
  return createDocument(bodyFile, title);
}

File creation

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);

}

The error I get in my log

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

I got rid of the .Dispose method and changed. var fstemp = new FileStream(newPath ... Now I can send several attachments. But now they randomly give an error or not. 4 out of 5 times it works. The 4th time, he again gives an error that he cannot open the file. 5th time, it magically works again.

EDIT: solution

. . Tnx to @HatSoft @Aghilas Yakoub

+5
3

( CreateDocument):

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

3 ?

attachment.Dispose(); 

, Mail . .

+2

It looks like newPath in FileStream fs = File.Create (newPath); incorrectly, and the file is not created, looking at the fact that the new code will end with "Documents" and the file name File.Create with the extension, therefore, they will not be attached.

0
source

All Articles