簡體   English   中英

IOException:該進程無法訪問文件,因為它正在被另一個進程使用

[英]IOException: The process cannot access the file because it is being used by another process

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

您應該嘗試在發送郵件后調用attachment.Dispose()

為此,聲明Attachment attachment; if (url != null)並在client.Send(mailMessage); Dispose()之后調用Dispose() client.Send(mailMessage); 如果attachment != null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM