iTextSharp的不关闭文件 [英] itextsharp not closing files
问题描述
我有一些code为iTextSharp的合并2 PDF文件。在网上找到它的地方。合并工作正常,但似乎源文件是住在使用后,它是所有完成。我想要做的是删除,我已经合并的第一个文件,这是通过一个FileUpload上传,只保留合并的文件。这绝对是code这样做,是导致文件保持开放的合并。我试图删除服务器上的文件,它告诉我类似的东西是由IIShelper开放。通过工作时间我收窄至下降到这个东西。为什么保持在文件中使用?
I've got some code for itextsharp merging 2 pdf files. Found it online somewhere. The merging works fine, but it seems that the source files are staying in use after it is all done. What I'd like to do is to delete the first file that i have already merged, which is uploaded via a fileupload, and keep only the merged file. It's definitely the code doing the merging that is causing the file to stay open. I tried to delete the file on the server and it tells me something like it's open by the IIShelper. Through hours of work I narrowed to down to this stuff. Why is it keeping the file in use?
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
if(reader.IsEncrypted() == false)
{
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
}
}
}
else
{
//is encrypted
}
// step 5: we close the document
document.Close();
reader.Close();
reader.Dispose();
}
在此先感谢
推荐答案
您只关闭每个文件一个读
结尾,但开放合一读卡器。因此,只有最后一个读
将得到休息。
You are only closing one reader
at the end, but opening one reader per file. Thus, only the last reader
will get closed.
您需要在此之前,关闭旧的阅读器
You need to close the old reader before you do
reader = new PdfReader(sourceFiles[f]);
这篇关于iTextSharp的不关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!