繁体   English   中英

发送电子邮件后无法删除PDF文件

[英]Unable to delete PDF file after sending email

我的代码处理信息,然后将网站导出到Word文档,然后将其转换为PDF并继续将其附加到电子邮件代码中。 我已设法发送包含PDF的电子邮件,但文件管理存在问题。 在这种情况下,我想删除文件夹中的文件,即生成的单词和PDF文档。 代码运行并能够删除word文档但无法删除PDF文档。

手动尝试删除文件时出现的错误是“无法完成操作,因为文件已在webdev.webserver40.exe中打开”。 目前正在调试模式下运行,并希望将来在IIS上运行它。

以下是我的电子邮件代码的片段

Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False

            e_mail = New MailMessage()                
            e_mail.Subject = "Job Completed "
            e_mail.IsBodyHtml = False
            e_mail.Body = msg
            e_mail.Attachments.Add(New Attachment(Server.MapPath("PDF\" + filename + ".pdf")))
            Smtp_Server.Send(e_mail)
            Smtp_Server.Dispose()
            e_mail.Attachments.Clear()
            e_mail.Dispose()

删除了身份验证和发送地址。 以下是删除文件的代码

Dim filePaths As String() = Directory.GetFiles(HttpContext.Current.Server.MapPath("PDF"))
        For Each filePath As String In filePaths
            File.Delete(filePath)
        Next

下面是用于转换pdf的类文件

    Imports Microsoft.VisualBasic
Imports System.IO
Imports Microsoft.Office.Interop.Word

Public Class ConvertWordToPDF
    Public Sub convertToPDF(strFileName As String)
        ' Create a new Microsoft Word application object
        Dim word As New Microsoft.Office.Interop.Word.Application()

        ' C# doesn't have optional arguments so we'll need a dummy value
        Dim oMissing As Object = System.Reflection.Missing.Value

        ' Get list of Word files in specified directory
        Dim dirInfo As New DirectoryInfo(HttpContext.Current.Server.MapPath("PDF"))
        Dim wordFiles As FileInfo() = dirInfo.GetFiles("*.docx")
        word.Visible = False
        word.ScreenUpdating = False

        ' Cast as Object for word Open method
        Dim filename As [Object] = DirectCast(wordFiles(0).FullName, [Object])
        'Dim fileName As Object = strFileName

        ' Use the dummy value as a placeholder for optional arguments
        Dim doc As Document = word.Documents.Open(fileName, oMissing, oMissing, oMissing, oMissing, oMissing, _
         oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
         oMissing, oMissing, oMissing, oMissing)
        doc.Activate()

        Dim outputFileName As Object = wordFiles(0).FullName.Replace(".docx", ".pdf")
        Dim fileFormat As Object = WdSaveFormat.wdFormatPDF

        ' Save document into PDF Format
        doc.SaveAs(outputFileName, fileFormat, oMissing, oMissing, oMissing, oMissing, _
         oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
         oMissing, oMissing, oMissing, oMissing)

        ' Close the Word document, but leave the Word application open.
        ' doc has to be cast to type _Document so that it will find the
        ' correct Close method.                
        Dim saveChanges As Object = WdSaveOptions.wdDoNotSaveChanges
        DirectCast(doc, _Document).Close(saveChanges, oMissing, oMissing)

        doc = Nothing

        ' word has to be cast to type _Application so that it will find
        ' the correct Quit method.
        DirectCast(word, _Application).Quit(oMissing, oMissing, oMissing)
        word = Nothing
    End Sub
End Class

编辑:添加代码以检查文件是否已锁定

Protected Overridable Function IsFileLocked(file As FileInfo) As Boolean
    Dim stream As FileStream = Nothing

    Try
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
    Catch generatedExceptionName As IOException
        'the file is unavailable because it is:
        'still being written to
        'or being processed by another thread
        'or does not exist (has already been processed)
        Return True
    Finally
        If stream IsNot Nothing Then
            stream.Close()
        End If
    End Try

    'file is not locked
    Return False
End Function

在创建pdf后它返回false。

刚刚测试了我能够重现问题的场景。 我能够通过将附件添加为流而不仅仅是文件的路径来修复它。 只记得以这种或那种方式关闭流。

此代码提供您描述的错误:

    Dim smtp As New SmtpClient("...") 

    message.Attachments.Add(New Attachment("c:\myfile.txt"))
    smtp.Send(message)

    File.Delete("c:\myfile.txt")

这有效:

   Dim smtp As New SmtpClient("...")

    Using reader As New StreamReader("C:\myfile.txt")
        Dim a As New Attachment(reader.BaseStream, "myfile.txt")
        message.Attachments.Add(a)

        smtp.Send(message)
    End Using      

    File.Delete("c:\myfile.txt")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM