加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

.net – 文件在被SmtpClient作为附件发送后似乎保持打开状态.我

发布时间:2020-12-17 00:19:36 所属栏目:大数据 来源:网络整理
导读:我有一些函数生成的文件定义为: 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 Gen
我有一些函数生成的文件定义为:
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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读