附加到其他 PDF 文件后无法删除 PDF 文件 - C# - ItextSharp

Unable to Delete PDF File After Appending to Other PDF File - C# - ItextSharp

我正在尝试使用 iTextSharp 库将 PDF 文件加载到一个新的 PDF 中,我想在完成后删除单个文件(从 .DOC 格式转换而来) .

这是最后一段代码,它附加了所有文件,这就是我认为问题所在:

    static void Concat(string targetPdf, string[] newPdfFiles)
    {
        using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
        {
            iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4);

            PdfCopy pdf = new PdfCopy(pdfDoc, stream);
            pdfDoc.Open();
            int i = 1;
            foreach (string file in orderedlist)
            {
                if (!(file.Contains("HR Policies and Procedures Guide")))
                {
                    var newFileName = "\\file\IT\SK\test\" + file.Split('.')[0] + ".pdf";
                    pdf.AddDocument(new PdfReader(newFileName));
                }
                i++;
            }

            pdf.Close();
            pdfDoc.Dispose();
        }
    }

在使用 pdf.AddDocument(new PdfReader(newFileName)); 之前,我可以使用 System.IO.File.Delete("\\Path\To\File.pdf");

毫无问题地删除任何 PDF 文件

但是,如果我在 运行 AddDocument 之后尝试这样做,我会看到以下异常:

An unhandled exception of type 'System.IO.IOException' occurred in     mscorlib.dll

Additional information: The process cannot access the     file '\file\IT\SK\test\HR Policies and Procedures Acceptance Form.pdf' because it is being used by another process.

我试过对 pdf 和 pdfDoc 变量调用 .Close() 和 .Dispose() 但没有成功。

我也检查了我目前是哪些进程 运行 Process Explorer,但是太多了我不知道从哪里开始。

有没有人知道我该如何克服这个问题?

正如 Skuzzbox 在评论中提到的,真正的罪魁祸首是 PdfReader,我最初是在调用 pdf.AddDocument 的同时声明的(见问题)。

但是,先声明它,调用它,然后单独处理该变量,释放了 pdf 文件,这样我就可以自由删除它了:

    static void Concat(string targetPdf, string[] newPdfFiles)
    {
        using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
        {
            iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4);

            PdfCopy pdf = new PdfCopy(pdfDoc, stream);
            pdfDoc.Open();
            foreach (string file in orderedlist)
            {
                if (!(file.Contains("HR Policies and Procedures Guide")))
                {
                    var newFileName = "\\file\IT\SK\test\" + file.Split('.')[0] + ".pdf";

                    PdfReader test = new PdfReader(newFileName);
                    pdf.AddDocument(test);
                    test.Dispose();

                    // Delete the individual pdf ..
                    System.IO.File.Delete(newFileName);
                }

                pdfDoc.Close();
                pdf.Close(); 
            }
        }
    }

这是有道理的,因为这是实际捕获文件的变量。当我试图处理/关闭的其他进程正在处理文件时,PdfReader 变量代表实际的 pdf 文件。

编辑 添加了 pdf.Close();pdfDoc.Close(); 因为没有这些 pdf 最终文件已损坏