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 Word 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.
 
There are a few APIs/tools that provide the facility to secure a lot of file formats. Have a look at the GroupDocs.Merger for .NET code below.
  1. string password = "iamironman";  
  2. Stream openFile = new FileStream(sourceFile, FileMode.Open);  
  3. DocumentResult result = new DocumentHandler().AddPassword(openFile, password);  
  4. Stream documentStream = result.Stream;  
I have attached a sample project for testing purposes. You just have to pass a source file and define the output path in the project. 
 
One interesting thing about this API is that it gives you two options,
  • 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")
  • 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)