[英]Unable to delete PDF file after sending email
My code process the information an a website then exports it to word documents then converts it to PDF and proceeds to attach it onto an email code. 我的代码处理信息,然后将网站导出到Word文档,然后将其转换为PDF并继续将其附加到电子邮件代码中。 I've managed to send the email with the PDF but have problems with the file management.
我已设法发送包含PDF的电子邮件,但文件管理存在问题。 In this case I would want to delete the files in the folder namely, the generated word and PDF document.
在这种情况下,我想删除文件夹中的文件,即生成的单词和PDF文档。 The code runs and was able to delete the word document but unable to delete the PDF document.
代码运行并能够删除word文档但无法删除PDF文档。
The error when I manually tried to delete the file was "The action can't be completed because the file is open in webdev.webserver40.exe". 手动尝试删除文件时出现的错误是“无法完成操作,因为文件已在webdev.webserver40.exe中打开”。 Currently running on debug mode and wish to run this on an IIS in the future.
目前正在调试模式下运行,并希望将来在IIS上运行它。
Below is the snippet of my email code 以下是我的电子邮件代码的片段
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()
Removed authentication and sending address. 删除了身份验证和发送地址。 Below is the code to delete the files
以下是删除文件的代码
Dim filePaths As String() = Directory.GetFiles(HttpContext.Current.Server.MapPath("PDF"))
For Each filePath As String In filePaths
File.Delete(filePath)
Next
below is the class file that is used to convert the pdf 下面是用于转换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
Edit: Added code to check if the file is locked 编辑:添加代码以检查文件是否已锁定
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
it returned false after the pdf was created. 在创建pdf后它返回false。
Just tested a scenario where i was able to reproduce the problem. 刚刚测试了我能够重现问题的场景。 I was able to fix it by adding the attachment as a stream rather than just a path to the file.
我能够通过将附件添加为流而不仅仅是文件的路径来修复它。 Just remember to close the stream one way or another.
只记得以这种或那种方式关闭流。
This code gives the error you descriped: 此代码提供您描述的错误:
Dim smtp As New SmtpClient("...")
message.Attachments.Add(New Attachment("c:\myfile.txt"))
smtp.Send(message)
File.Delete("c:\myfile.txt")
This works: 这有效:
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.