Search code examples
c#itext

C# iTextSharp: The process cannot access the file because it is being used by another process


I'm generating a pdf file from a template with iTextSharp, filling each field in this code portion:

        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();
        }

Everything goes fine, file looks ok, but when i try to reopen the file to merge it with some other files I've generated in a unique document i get this error:

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.

Error occurs at this point

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

Edit: Using Process monitor as suggested I can see there is no close CloseFile operation as I would expect. Can this be the source of the issue?

I've been stuck on this for hours any help is really really appreciated.


Solution

  • Had the same issue with me. This helped a lot.

    "You're problem is that you are writing to a file while you are also reading from it. Unlike some file types (JPG, PNG, etc) that "load" all of the data into memory, iTextSharp reads the data as a stream. You either need to use two files and swap them at the end or you can force iTextSharp to "load" the first file by binding your PdfReader to a byte array of the file."

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

    Ref: Cris Haas answer to Cannot access the file because it is being used by another process