微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/vb/255450.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐