文件似乎在被SmtpClient作为附件发送后保持打开状态.我该如何删除文件?

Fro*_*840 7 .net vb.net email smtpclient

我有一些函数生成的文件定义为:

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
Run Code Online (Sandbox Code Playgroud)

立即打印这些文件,文件自动保存到目录中; 文件本身不供实际软件用户使用.我对文件加时间戳,以便将它们唯一标识用于审计目的.

我现在已经收到要求将这些文件的一些外部邮件发送到公司,并且有人抱怨当前的文件名不是用户友好的.

因此,我尝试将生成的文件复制到临时目录,使用更友好的名称,通过电子邮件发送友好文件,然后删除它,使我的审计跟踪保持原样,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

由于该文件在通过电子邮件发送后仍处于使用状态,因此会抛出System.IO.IOException该行System.IO.File.Delete(friendlyFilePath).

我已经取出了电子邮件代码,这使得复制和删除工作正常,因此它显然将文件附加到导致问题的电子邮件中.

我还尝试在删除行之前进行断点操作,等待五分钟,确认电子邮件已发送,然后推进代码,但仍然抛出相同的异常.

任何人都可以建议如何解决这个问题?

小智 13

mailClient.Send(message);添加之后message.Attachments.Dispose();

这将释放附件资源


Gra*_* H. 7

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);
}
Run Code Online (Sandbox Code Playgroud)