C# iTextSharp:进程无法访问该文件,因为它正被另一个进程使用

LNy*_*rla 1 c# itextsharp

我正在使用 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();
        }
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

此时出现错误

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

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

我已经坚持了几个小时,真的很感激任何帮助。

Mah*_*din 5

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

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

PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath));
Run Code Online (Sandbox Code Playgroud)

参考:Cris Haas 回答无法访问该文件,因为它正被另一个进程使用