ItextSharp锁定所有文件
问题描述:
我使用了itext sharp来合并一些pdf。之后,我想删除它们。 但是itextsharp不会关闭文件,并且File.Delete会引发异常。ItextSharp锁定所有文件
这是我的代码:
Dim mergedPdf As Byte() = Nothing
Using ms As New MemoryStream()
Using document As New Document()
Using copy As New PdfCopy(document, ms)
document.Open()
'_listaPath is a List (of String) with the paths off all pdf to merge
For i As Integer = 0 To _listaPDF.Count - 1
Dim reader As New PdfReader(_listaPDF(i))
' loop over the pages in that document
Dim n As Integer = reader.NumberOfPages
Dim page As Integer = 0
While page < n
copy.AddPage(copy.GetImportedPage(reader, System.Threading.Interlocked.Increment(page)))
End While
Next
End Using
End Using
mergedPdf = ms.ToArray()
End Using
File.WriteAllBytes(fileexplorer.FileName, mergedPdf)
For Each pdfTMP In _listaPDF
If File.Exists(pdfTMP) Then
File.Delete(pdfTMP)
End If
Next
_listaPDF = New List(Of String)
答
我发现这个问题。
此行
Dim reader As New PdfReader(_listaPDF(i))
应该
Using reader As New PdfReader(_listaPDF(i))
结论,我需要更多的咖啡
我没有看到'document.Close()'任何地方。请关闭文档以释放流。我没有在任何地方看到'reader.Close()'。关闭阅读器实例以释放流。 – 2014-12-02 18:48:46
“使用”应该为我做。尽管在我的一个测试中,我在每个“结束使用”之前都写了:x.dispose()和x.close。我更新我的问题whith代码的测试。同样的结果 – Rumpelstinsk 2014-12-02 18:55:40