Encrypt and decrypt word document for WPF applications

With the help of Spire.Doc for WPF, developers can create and edit word documents easily and flexibly for their WPF applications. Sometimes developers need to protect their word documents for being read and edit by others. They may need to add password for the word files to protect them confidential. Then others have to enter the password to open the view the encrypted word documents. Spire.Doc for WPF offers a method of Document.Encrypt(); to enable developers to set the password for word documents and Document.RemoveEncryption(); to remove the encryption for word documents.

This article will demonstrate how to encrypt and word documents with password and decrypt the word documents in C# for WPF applications.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("Sample.docx");

Step 2: Encrypt the document with password.

document.Encrypt("eiceblue");

Step 3: Save the encrypted document to file.

document.SaveToFile("Encryption.docx", FileFormat.Docx);

Step 4: Create a second new word document and load the encrypted document from file with the password.

Document document2 = new Document();
document2.LoadFromFile("Encryption.docx",FileFormat.Docx,"eiceblue");

Step 5: Decrypted the word document.

document2.RemoveEncryption();

Step 6: Save the decrypted document to file.

document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

Please check the effective screenshots of the encrypted word document and the decrypted word documents as below:

Encrypted document with password:

Encrypt and decrypt word document for WPF applications

Decrypted word document:

Encrypt and decrypt word document for WPF applications

Full codes:

using Spire.Doc;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();
            document.LoadFromFile("Sample.docx");

            document.Encrypt("eiceblue");

            document.SaveToFile("Encryption.docx", FileFormat.Docx);

            Document document2 = new Document();
            document2.LoadFromFile("Encryption.docx", FileFormat.Docx, "eiceblue");
            document2.RemoveEncryption();

            document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

        }
    }
}