0

what's wrong with my code?? am i missing something? i failed to delete the file, it show error "it is being used by another process. Please help

            string filename = "C:/File/testExport_1234.pdf";
            string htmlfile = "C:/file/1234.html";

            using (StreamReader reader = new StreamReader(htmlfile))
            {
                MailMessage message = new MailMessage(emailFrom, emailTo, emailSubject, reader.ReadToEnd());
                message.IsBodyHtml = true;

                Attachment data = new Attachment(filename, MediaTypeNames.Application.Octet);

                data.Name = filename;  // set name here
                message.Attachments.Add(data);

                SmtpClient client = new SmtpClient("smtp.live.com");
                client.UseDefaultCredentials = false;
                client.Port = 587;
                client.EnableSsl = true;
                client.Credentials = new NetworkCredential("xxxxx@hotmail.com", "xxxxx", "hotmail.com");

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
                                ex.ToString());
                }
            }

            if (File.Exists(filename))
            {

                File.Delete(filename);
                //File.Delete(path + code + ".html");
            }
sigmax bpo
  • 27
  • 1
  • 9
  • Take a look at that thread: https://stackoverflow.com/questions/2781103/c-sharp-how-to-correctly-dispose-of-an-smtpclient You must dispose SmtpClient and Attachments – Marc Mar 28 '18 at 06:15
  • Thanks alot @Marc !! got it!! – sigmax bpo Mar 28 '18 at 06:19

1 Answers1

1

You need to dispose the SMTP Client and also MailMessage.Use a Using statement :

 using (MailMessage Message = new MailMessage)
{ .....
   .......
    using (SmtpClient client = new SmtpClient)
    {
     .........
    }
}

To dispose attachments,call :

DisposeAttachments();
Software Dev
  • 5,368
  • 5
  • 22
  • 45