【问题标题】:C# iTextSharp: The process cannot access the file because it is being used by another processC# iTextSharp:该进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2015-11-23 10:45:24
【问题描述】:

我正在使用 iTextSharp 从模板生成一个 pdf 文件,并填充此代码部分中的每个字段:

        PdfReader pdfReader = new PdfReader(templatePath);
        try
        {
            using (FileStream newFileStream = new FileStream(newFilePath, FileMode.Create))
            {
                using (PdfStamper stamper = new PdfStamper(pdfReader, newFileStream))
                {
                    // fill each field
                    AcroFields pdfFormFields = stamper.AcroFields;
                    foreach (KeyValuePair<string, string> entry in content)
                    {
                        if (!String.IsNullOrEmpty(entry.Value))
                            pdfFormFields.SetField(entry.Key, entry.Value);
                    }

                    //The below will make sure the fields are not editable in
                    //the output PDF.
                    stamper.FormFlattening = true;
                    stamper.Close();
                }                    
            }
        }
        finally
        {
            pdfReader.Close();
        }

一切正常,文件看起来不错,但是当我尝试重新打开文件以将其与我在唯一文档中生成的其他文件合并时,我收到此错误:

2015-11-23 09:46:54,651||ERROR|UrbeWeb|System.IO.IOException: The process cannot access the file 'D:\Sviluppo\communitygov\MaxiAnagrafeImmobiliare\MaxiAnagrafeImmobiliare\cache\IMU\E124\admin\Stampe\Provvedimento_00223850306_2015_11_23_094654.pdf' because it is being used by another process.

此时出现错误

foreach (Documento item in docs)
{                                      
           string fileName = item.FilePath;
           pdfReader = new PdfReader(fileName); // IOException
           // some other operations ...                    
}

编辑:按照建议使用进程监视器,我可以看到没有像我预期的那样关闭 CloseFile 操作。这可能是问题的根源吗?

我已经坚持了好几个小时了,真的非常感谢任何帮助。

【问题讨论】:

  • 您是否尝试过使用源代码进行调试(它们可用)?用 FileMon 查看文件句柄?
  • 您是否打开了任何 PDF 文件,例如Adobe阅读器?某些应用程序会在打开文件时锁定文件以进行编辑。
  • 另一个小点:你关闭了stamperpdfReader,但你没有关闭newFileStreamusing 无论如何都应该处理掉它,所以它可能没有任何区别......
  • @LNyarla, PdfStamper 可以绑定到Stream 的任何子类,所以mkl 的意思是使用MemoryStream 而不是FileStream,只需将PDF 作为字节数组获取在MemoryStream 上使用ToArray()。此外,您会看到 Close() 经常被调用,但正如您所指出的并且 mkl 响应它是不需要的。这只是“如果您打开某些东西就应该关闭它”心态的产物(我总是这样做),但您可以跳过它。

标签: c# itextsharp


【解决方案1】:

和我有同样的问题。这帮助很大。

“你的问题是你在写入文件的同时也在读取它。与将所有数据“加载”到内存中的某些文件类型(JPG、PNG 等)不同,iTextSharp将数据作为流读取。您要么需要使用两个文件并在最后交换它们,要么可以通过将 PdfReader 绑定到文件的字节数组来强制 iTextSharp “加载”第一个文件。”

PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath));

参考:Cris Haas 回复 Cannot access the file because it is being used by another process

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2010-12-10
    相关资源
    最近更新 更多