How to detect if a PDF document is password protected in C#, VB.NET

A PDF document encrypted with a user password legally cannot be opened without the password. We’d better detect if a document is password protected or not before we try to open it. This article presents how to determine if a PDF document is encrypted with password using Spire.PDF in C#, VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class.

PdfDocument doc = new PdfDocument();

Step 2: Load a sample PDF document.

doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

Step 3: Detect whether the document is encrypted with password or not.

bool isEncrypted = doc.IsEncrypted;
Console.WriteLine(isEncrypted);

Result:

How to detect if a PDF document is password protected in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");

bool isEncrypted = doc.IsEncrypted;
Console.WriteLine(isEncrypted);
Console.Read();
[VB.NET]
Dim doc As New PdfDocument()
doc.LoadFromFile("C:\Users\Administrator\Desktop\Encrypted.pdf")

Dim isEncrypted As Boolean = doc.IsEncrypted
Console.WriteLine(isEncrypted)
Console.Read()