.net – 文件在被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

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

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

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

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.File.Delete(friendlyFilePath)行上引发System.IO.IOException,因为该文件在通过电子邮件发送后仍在使用中.

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

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

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

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);
}

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...