Search code examples
c#mailmessage

c# failed delete file, it is being used by another process


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("[email protected]", "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");
            }

Solution

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