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

时间:2014-06-24 08:06:45

标签: vb.net visual-studio-2010 file email email-attachments

我的代码处理网站上的信息,然后将其导出到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。

1 个答案:

答案 0 :(得分:1)

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

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

    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")