Search code examples
itext7

iText7 - PdfReader constructor locks non-pdf files


Consider the following C# code:

try
{
    using (new PdfReader(filename))
    {
    }
}
catch
{
}
finally
{
    File.Delete(filename);
}

If filename points to a non-pdf file, PdfReader constructor throws exception (as expected), but also does not release the FileStream that it internally creates, despite being called in a using block. As a result, attempt to delete the file in finally block throws exception The process cannot access the file '<filename>' because it is being used by another process.

In fact, if constructor throws an exception, it should not result in locking any resources. So the above code should be deleting non-pdf files even when PdfReader constructor is called without the using block.

Obvious workaround is to instantiate PdfReader like this:

using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
using (new PdfReader(fileStream))
{
}

It does work, but current behaviour of the PdfReader constructor overloads using filename argument is not expected.


Solution

  • This is indeed a bug on the part of iText, but it's known issue and it's already fixed in the newest develop version. iText 7.1.16 version will contain this fix, but if you need this right now you can use SNAPSHOT version from the artifactory https://repo.itextsupport.com/webapp/#/artifacts/browse/tree/General/snapshot