c#删除文件失败,正被另一个进程使用

时间:2018-03-28 06:13:02

标签: c# mailmessage

我的代码出了什么问题?我错过了什么吗?我没有删除该文件,它显示错误“它正被另一个进程使用。请帮助

            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");
            }

1 个答案:

答案 0 :(得分:1)

您需要处置SMTP客户端以及MailMessage.Use Using声明:

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

要处置附件,请致电:

DisposeAttachments();