Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple attachments in c#

I'm having problems, while sending multiple attachments in my program.

I didn't have any problems before I tried to add multiple attachments. So I changed to code a bit and it stopped working.

Create attachment: Didn't add all the code to make it more viewable.

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 Attachment

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

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

}

The error I get in my 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

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

EDIT: Solution

I used a using block in combination with two answers. And that worked. Tnx to @HatSoft and @Aghilas Yakoub

like image 764
Sllix Avatar asked Oct 08 '22 07:10

Sllix


1 Answers

Try it with these lines (in your CreateDocument method):

var fstemp = new FileStream(newPath, FileMode.Open, FileAccess.Read);
return new Attachment(fstemp, title, MediaTypeNames.Application.Octet);
like image 83
Aghilas Yakoub Avatar answered Oct 13 '22 11:10

Aghilas Yakoub