The requested page is not available for the requested platform. You are viewing the content for .NET Framework 4.5.2+ platform.

How to: Protect a Document

  • 2 min to read

Document protection prevents end-users from modifying a document (by adding, formatting or deleting the document parts, inserting tables, images, comments, etc.).

The following example demonstrates how to protect a document by calling the Document.Protect method :

server.LoadDocument("Documents//Grimm.docx",DocumentFormat.OpenXml);
Document document = server.Document;
if (!document.IsDocumentProtected)
{
    //Protect the document with a password
    document.Protect("123",DocumentProtectionType.ReadOnly);

    //Insert a comment indicating that the document is protected
    document.Comments.Create(document.Paragraphs[0].Range, "Admin");                
    SubDocument commentDocument = document.Comments[0].BeginUpdate();                
    commentDocument.InsertText(commentDocument.CreatePosition(0), 
    "Document is protected with a password.\nYou cannot modify the document until protection is removed.");
    commentDocument.EndUpdate();
}

Unprotect a Document

Use the Document.Unprotect method to remove protection.

server.LoadDocument("Documents//Grimm_Protected.docx", DocumentFormat.OpenXml);
Document document = server.Document;

if (document.IsDocumentProtected == true)
{
    //Unprotect the document
    document.Unprotect();

    //Insert a comment indicating that the document can be edited
    document.Comments.Create(document.Paragraphs[0].Range,"Admin");
    SubDocument commentDocument = document.Comments[0].BeginUpdate();
    commentDocument.InsertText(commentDocument.CreatePosition(0),
   "Document is unprotected. You can modify the document according to your requests.");
    commentDocument.EndUpdate();
}