IOException:进程无法访问该文件,因为它正由另一个进程使用

时间:2018-04-10 13:58:09

标签: c# asp.net-core

我在访问ASP.NET Core控制器的操作时尝试发送带附件的电子邮件。附件由将html页面导出为pdf的站点下载。该函数发送电子邮件但它不能删除附件文件,因为它仍然被另一个进程使用。 错误在哪里?

public void SendAsHtml(string body, string subject, string emailTo, string url = null, string fileName = null)
{
    string path = null;
    using (SmtpClient client = GetSmtpClient())
    {
        MailMessage mailMessage = new MailMessage
        {
            From = new MailAddress(sendemail),
            Body = body,
            Subject = subject,
            IsBodyHtml = true
        };
        mailMessage.To.Add(emailTo);

        if (url != null)
        {
            if (fileName == null)
            {
                fileName = DateTime.Now.ToString("yyyyMMddHHmmss.pdf");
            }

            if (!fileName.EndsWith(".pdf"))
            {
                fileName += ".pdf";
            }
            path = @"c:\temp\" + fileName;
            DeleteFile(path);
            using (WebClient myWebClient = new WebClient())
            {
                myWebClient.DownloadFile($"{htmlToPdfServer}?url=" + url, path);
            }

            Attachment attachment = new Attachment(path);
            mailMessage.Attachments.Add(attachment);
        }

        client.Send(mailMessage);
    }

    if (path != null)
    {
        // it does not work
        DeleteFile(path);
    }
}


private static void DeleteFile(string path)
{
    try
    {
        if (File.Exists(path))
        {
            File.Delete(path);
        }
    }
    catch (Exception ex)
    {
        Log.Warning($"Send email service: cannot delete file {path} {ex.Message}");
    }
}

1 个答案:

答案 0 :(得分:2)

发送邮件后,您应该尝试拨打attachment.Dispose()

要执行此操作,请在Attachment attachment;之前声明if (url != null),并在Dispose() client.Send(mailMessage);之后致电attachment != null