【问题标题】:Unable to delete PDF file after sending email发送电子邮件后无法删除 PDF 文件
【发布时间】:2014-06-24 08:06:44
【问题描述】:

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

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

下面是我的邮箱代码的sn-p

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。

【问题讨论】:

  • 检查包含您的文件的文件夹的属性。是否设置为“所有人”,或者至少允许“网络服务”(IIS 帐户)?
  • 喜欢在文件夹的安全选项卡中?
  • 是的,属性 > 安全性。
  • 我怀疑它与文件夹有关,因为我的 word 文档已从同一文件夹中成功删除,但 PDF 无法删除。我需要某种代码,否则处置工作不正常。
  • 好的,你能把你的pdf生成器功能放上去吗?文件似乎没有正确关闭。

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


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2011-06-22
    相关资源
    最近更新 更多