Itextsharp Pdfreader Lock the file, how can I avoid it?

290 views Asked by At

I refer to this post: How to decrypt a pdf file by supplying password of the file as argument using c#?

(In this post I cannot answer due to reputation, so please help me)

The exact solution in that post is the one I've been using for years. This is the code

private void DecryptFile(string inputFile, string outputFile)
{
   string password = @"secret"; // Your Key Here
   enter code here
   try
   {
      // the file crashes after this instruction
    PdfReader reader = new PdfReader(inputFile, new System.Text.ASCIIEncoding().GetBytes(password));

        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfStamper stamper = new PdfStamper(reader, memoryStream);
            stamper.Close();
            reader.Close();
            File.WriteAllBytes(outputFile, memoryStream.ToArray());
        }

    }
    catch (Exception err)
    {
      Console.WriteLine(err.Message);
    }
}

It works perfectly, but if the password is wrong there is a big problem.

The file is locked by the application. In my case the problem is even greater since it is not a windows application, but a windows service, therefore telling the customer "stop the service and delete the file" is not an optimal solution.

How can I prevent the file from getting stuck?

0

There are 0 answers