DEV Community

Atir Tahir
Atir Tahir

Posted on • Originally published at blog.groupdocs.com

2 1

Add Password Protection To Word Or PDF Files In C#

Everything is going digital. There are outstanding products/tools to pull you into the paperless era. We share information across companies or anywhere in the form of different file formats. It could be a Spreadsheet, PDF, or any of the MS Office formats. But the biggest threat is security. Let’s understand this with a use-case.

You want to secure a Spreadsheet or PDF file on a machine where MS Office or Adobe PDF is not installed, in that case, you need a tool or API that can secure such documents programmatically without any dependency.
Have a look at the GroupDocs.Merger for .NET code below.

string password = "iamironman";
Stream openFile = new FileStream(sourceFile, FileMode.Open);
DocumentResult result = new DocumentHandler().AddPassword(openFile, password);
Stream documentStream = result.Stream;
var fileStream = File.Create(CommonUtilities.outputPath + "OutPut." + result.FileFormat);
documentStream.CopyTo(fileStream);
documentStream.Close();
view raw securedoc.cs hosted with ❤ by GitHub

One interesting thing about this API is that it gives you two options,

  1. Pass a source file and specify its extension as well and save output/protected file with the same extension (source: “test.pdf”, output: “test.pdf”)
  2. Secondly, you can pass the source file and for the output you just have to specify the file name and the API will detect file extension on its own based on the source file (source: “test.pdf”, output: “test.”+result.FileFormat)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay