Control Exception PDF File
Contents
[
Hide
]
PdfFileSecurity class allows you to control exceptions. To do this, you need to set AllowExceptions property to false or true. If you set the operation to false, the result of DecryptFile will return true or false depending on the correctness of the password.
public static void ControlExceptionPDFFile()
{
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.BindPdf(dataDir + "sample_encrypted.pdf");
fileSecurity.AllowExceptions = false;
// Decrypt PDF document
if (!fileSecurity.DecryptFile("IncorrectPassword"))
{
Console.WriteLine("Something wrong...");
Console.WriteLine($"Last exception: {fileSecurity.LastException.Message}");
}
fileSecurity.Save(dataDir + "sample_decrtypted.pdf");
}
If you set AllowExceptions property to true, then you can get the result of the operation using the try-catch operator.
public static void ControlExceptionPDFFile2()
{
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.BindPdf(dataDir + "sample_encrypted.pdf");
fileSecurity.AllowExceptions = true;
try
{
// Decrypt PDF document
fileSecurity.DecryptFile("IncorrectPassword");
}
catch (Exception ex)
{
Console.WriteLine("Something wrong...");
Console.WriteLine($"Exception: {ex.Message}");
}
fileSecurity.Save(dataDir + "sample_decrtypted.pdf");
}