【发布时间】: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