-2

In my site, User uploads some file from his system and sends email.

try
{
  if(Request.Files!=null)
  {
     //save the file to some temp location 
     //Attach the file to email & send
  }
}
catch(Exception ex)
{
  //log exception
}
finally
{
    //delete the file from temp location
    System.IO.File.Delete(attachmentLocation);
}

But if email sendings fails, then I am able to delete the file but in case email is sent successfully,then I get an exception

The file test.pdf cannot be deleted, as its used by another process

Is it possible to attach the file without saving it?

In case not, then how I do delete the file after sending email?

FYI:- This is an AJAX call.

abc
  • 7
  • 6

2 Answers2

1

I think one of these two solutions can use the in the first link I think is the solution to your problem

"To Solve this problem, Basically you need to call Dispose ( ) on the MailMessage object ( Of which will then a call Dispose ( ) on the Attachment object , thereby releasing the lock on the file , and Allowing you to delete it) .

There are two obvious ways to do that:

1) Pass the MailMessage object to SendAsync () , via the UserToken argument . Then , in the SendCompletedCallback method , cast to the type MailMessage e.UserState , and call Dispose ( ) on it.

http://www.dreamincode.net/forums/topic/325303-c%23how-to-delete-attach-file-after-send-mail/

http://www.codeproject.com/Questions/360228/how-to-delete-attachment-file-after-it-is-send-as

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
1

You can achieve it withour saving file

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
{
    writer.Flush();
    stream.Position = 0;     

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

And now you just need to get memorystrem from your file

var postedFile = httpRequest.Files[0];
using (var binaryReader = new BinaryReader(postedFile.InputStream))
{
   var zz = new MemoryStream(binaryReader.ReadBytes(postedFile.ContentLength));
}
slava
  • 1,901
  • 6
  • 28
  • 32