holap
holap

Reputation: 438

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

I'm trying to send an email with attachment when I access an action of ASP.NET Core controller. The attachment is downloaded by a site that exports an html page to pdf. The function sends the email but it can't delete the attachment file because it is still used by another process. Where is the mistake?

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

Upvotes: 1

Views: 1687

Answers (1)

Patrick McDonald
Patrick McDonald

Reputation: 65421

You should try calling attachment.Dispose() after sending the mail message.

To do this, declare Attachment attachment; before if (url != null) and call Dispose() after client.Send(mailMessage); if attachment != null.

Upvotes: 2

Related Questions