0

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?

Aldo TKOL
  • 1
  • 1
  • 1
    I would assume the `PdfReader` implements `IDisposable`, so it should probably be in a `using(...)` statement. – JonasH Jul 21 '22 at 14:39
  • Indeed, putting the reader into a `using(...)` would be the first step. And if that doesn't suffice for which reason ever, consider first loading the file into a byte array and initializing the `PdfReader` from that byte array. – mkl Jul 21 '22 at 14:41
  • If `PdfReader` can take a stream, that might be a better alternative, since you can ensure that the stream is always disposed, even if the `PdfReader` does not do it. If neither works you should contact the vendor to make them fix their buggy implementation. If a class creates a resource, it should ensure proper disposal, even if an exception occurs. – JonasH Jul 21 '22 at 14:44
  • The problem is that these operations are done on many files with FileSystemWatcher and with Multi Thread. I tried using Using (...), it partially solves. I moved 4 files, the first 3 are not blocked, the last yes. With two files, the first does not block the last yes etc... – Aldo TKOL Jul 22 '22 at 14:00

0 Answers0