包含附件的SmtpClient.Send是否对附加文件保持锁定?

Cod*_*man 4 c# email smtp smtpclient

我正在调试一个问题,但在MSDN文档中找不到这个问题的答案

我有以下代码:

if(attachmentFileName != null && File.Exists(attachmentFileName))
{
    mail.Attachments.Add(new Attachment(attachmentFileName, MediaTypeNames.Application.Octet));
}

using(SmtpClient smtp = new SmtpClient { UseDefaultCredentials = true })
{
    try
    {
        smtp.Send(mail);
    }
    catch(SmtpException ex)
    {
        if(attachmentFileName != null && ex.StatusCode == SmtpStatusCode.ExceededStorageAllocation)
        {
            //Need to still send the mail. Just strip out the attachment & add footer saying that attachment has been stripped out.
            mail.Attachments.Clear();
            mail.Body += "\n\nNote: Please note that due to outbound size limitations, attachments to this email have been stripped out.\n";
            smtp.Send(mail);
        }
        else
        {
            throw;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在更高级别(此方法的调用者),我有以下内容:

try
{
    SendEmail(recipients, alertTitle, body, alertID, subjectPrefix, merchantIDValue, attachmentFilePath);
}
finally
{
    if(tempFile != null)
    {
        File.Delete(tempFile);
    }
}
Run Code Online (Sandbox Code Playgroud)

我将代码部署到我们的测试环境中,现在我的错误日志中出现以下异常:

System.IO.IOException: The process cannot access the file 'C:\fileName.zip' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)
   at AlertDelivery.CreateAttachmentFile(String attachmentData, String merchantID, String reportTitle) in d:\svn\trunk\Solution\Alerting\AlertDelivery.cs:line 143
   at AlertDelivery.TrySendAlert(String merchantID, String reportTitle, Int32 alertID, String alertTitle, String attachmentData, String attachmentFilePath, String body, Boolean isReport, String subjectPrefix, List`1 recipients) in d:\svn\trunk\Solution\Alerting\AlertDelivery.cs:line 110
   at AlertingService.ProcessAlertEvents(Object parameters) in d:\svn\trunk\Solution\Alerting\AlertingService.cs:line 174
Run Code Online (Sandbox Code Playgroud)

第174 File.Delete(tempFile);行是调用者代码中的行.

SmtpClient.Send调用后,SmtpClient是否在附件上保持异步锁定?还有其他明显的问题吗?

Ste*_*eve 10

尝试mail用using语句封装你的变量.
像这样

public void SendEmail(...)
{
    using(MailMessage mail = new MailMessage())
    {

      .... your code above
    }

}
Run Code Online (Sandbox Code Playgroud)

这将强制对MailMessage对象进行dispose调用,并且该调用也会处理任何附件.


Sam*_*Axe 7

它肯定会,直到你处理MailMessage对象.