Click here to Skip to main content
15,899,124 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using System.Net.Mail for sending mail in asp.net. how to delete attachment file after it is send as attachment mail. I tried to use File.Delete method.. but i am getting this error. the process cannot access the file path\123412.html' because it is being used by another process.please give me a best solution

I am using this code

C#
string mailUserName = ConfigurationManager.AppSettings["MailUsername"].ToString();
          string mailPassword = ConfigurationManager.AppSettings["MailPassword"].ToString();
          string mailHostAddress = ConfigurationManager.AppSettings["HostAddress"].ToString();

          MailMessage mail = new MailMessage(mailUserName, EmailAddress.ToString());
          mail.Body = "<FONT face=Arial Black color=#3377b4 size=3>Dear Customer;
          mail.Attachments.Add(new Attachment(pfname));
          mail.Subject = "Your Ticket(" + strSPNR + ") confirmation";
          mail.IsBodyHtml = true;

          SmtpClient smtp;
          System.Net.NetworkCredential basicAuth;


          //            mail.Body = "<FONT face=Arial Black color=#3377b4 size=3>Dear Customer;

          smtp = new SmtpClient();
          basicAuth = new System.Net.NetworkCredential(mailUserName, mailPassword);
          smtp.EnableSsl = false;
          smtp.Host = mailHostAddress;
          smtp.UseDefaultCredentials = false;
          smtp.Credentials = basicAuth;
          try
          {
              smtp.Send(mail);
              mail.Attachments.Clear();
              ((IDisposable)mail).Dispose();

              if (File.Exists(pfname))
              {
                   File.Delete(pfname);

              }

I am using this code. file saved in server path but file did not delete . I am using 'File.Delete(pfname);' . but file not deleting . how to solve............

regards
Posted
Updated 4-Apr-12 2:09am
v5
Comments
perilbrain 4-Apr-12 6:07am    
Did you close the connection ???? after sending the mail...???

My first thought would be the file in use exception is because the email client has not yet sent the message and still is using the file. You could write a timer service that clears the folder on a scheduled basis.
 
Share this answer
 
C#
try
            {
                smtp.Send(mail);
            }
              finally
            {
                  mail.Attachments.Clear();
                  if (File.Exists(pfname))
                {
                     File.Delete(pfname);
                    
                }
            }
 
Share this answer
 
i guess finally blocks works if you use Send method, but how to solve similar case if we send mail through SendAsync method
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900