我正在尝试使用 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 毫无问题地删除任何 PDF 文件("\\\\Path\\To\\File.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 最终文件已损坏
关于c# - 附加到其他 PDF 文件后无法删除 PDF 文件 - C# - ItextSharp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794035/