【问题标题】:IOException: The process cannot access the file because it is being used by another processIOException:该进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2018-09-20 04:31:31
【问题描述】:

当我访问 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}");
    }
}

【问题讨论】:

  • 处置,处置,处置,使用使用。
  • 你究竟是从哪里得到这个错误的? DeleteFile 函数长什么样子?
  • @Jerodev 我添加了 DeleteFile 代码。当我在 DeleteFile 中调用 File.Delete 时引发错误。
  • 您处理了很多东西,但仍然忘记了一个 - MailMessage 本身实现了 IDisposable。因此,也将其包装在 using 中。

标签: c# asp.net-core


【解决方案1】:

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

为此,请在if (url != null) 之前声明Attachment attachment;,如果attachment != null,则在client.Send(mailMessage); 之后调用Dispose()

【讨论】:

    猜你喜欢
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多