Dot-Net

文件在被 SmtpClient 作為附件發送後似乎保持打開狀態。如何刪除文件?

  • October 31, 2016

我有許多在定義為的函式中生成的文件:

Public Function GeneratePDF(exportFileName As String) As String
   Dim GeneratePath As String = FileSystem.CombinePath(standardDirectory, exportFileName  & DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") & ".pdf")
   If GenerateFile(GeneratePath) Then
       Return GeneratePath
   End If
   Return String.Empty
End Function

這些文件立即列印出來,並自動保存到一個目錄中;文件本身不供實際軟體使用者使用。我為文件添加時間戳以保持它們的唯一標識以用於審計目的。

我現在收到了將其中一些文件通過電子郵件發送給公司外部的要求,有人抱怨目前的文件名不便於使用者使用。

因此,我嘗試將生成的文件複製到一個臨時目錄,使用更友好的名稱,通過電子郵件發送更友好的文件,然後將其刪除,使我的審計跟踪保持不變,如下所示:

Public Function GeneratePDF(exportFileName As String) As String
   Dim GeneratePath As String = FileSystem.CombinePath(standardDirectory, exportFileName  & DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") & ".pdf")
   If GenerateFile(GeneratePath) Then

       Dim friendlyFilePath As String = FileSystem.CombinePath(standardDirectory, GetFriendlyFileName(GeneratePath))
       System.IO.File.Copy(GeneratePath, friendlyFilePath)

       Dim mailMsg As New System.Net.Mail.MailMessage
       Dim smtp As New System.Net.Mail.SmtpClient
       [Vast amount of code, which attaches friendlyFilePath to the email, then sends it]

       System.IO.File.Delete(friendlyFilePath)

       Return GeneratePath
   End If
   Return String.Empty
End Function

這會引發System.IO.IOException在​​線問題System.IO.File.Delete(friendlyFilePath),因為該文件在通過電子郵件發送後仍在使用中。

我已經取出了電子郵件程式碼,這使得複制和刪除工作正常,所以它顯然是將文件附加到導致問題的電子郵件中。

我也嘗試在刪除行之前設置斷點,等待五分鐘,確認電子郵件已發送,然後推程序式碼,但仍然拋出相同的異常。

誰能建議如何解決這個問題?

SmtpClient 不會釋放附件的句柄。您將不得不手動處理,或者,我所做的是首先將文件內容複製到 MemoryStream 中。下面的程式碼也應該可以工作。

using (MailMessage message = new MailMessage(from, to, subject, body))
using (Attachment attachment = new Attachment(fileName))
{
  message.Attachments.Add(attachment);
  mailClient.UseDefaultCredentials = true;
  mailClient.Send(message);
}

mailClient.Send(message);添加後message.Attachments.Dispose();

這將釋放附件資源

引用自:https://stackoverflow.com/questions/9196238