4

現在問題をデバッグしていますが、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;
        }
    }
}

より高いレベル (このメソッドの呼び出し元) では、次のようになります。

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

コードをテスト環境にデプロイしたところ、エラー ログに次の例外が記録されました。

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

行 174 はFile.Delete(tempFile);、呼び出し元コードの行です。

SmtpClient は、呼び出された後、添付ファイルの非同期ロックを維持しますSmtpClient.Sendか? 他に目立った問題はありますか?

4

2 に答える 2

10

mailusingステートメントを使用して変数をカプセル化してみてください
このようなもの

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

      .... your code above
    }

}

これにより、MailMessageオブジェクトのdispose呼び出しが強制され、その呼び出しによって添付ファイルも破棄されます。

于 2013-01-25T22:26:59.930 に答える
7

MailMessageオブジェクトを破棄するまでは、確かにそうです。

于 2013-01-25T22:24:49.130 に答える