A newer version of this page is available. Switch to the current version.

Document Protection

  • 2 minutes to read

Protect the Document from Editing

You can keep anyone from making changes in a document by enabling the document protection. Call the Document.Protect method to protect a document from editing using a given password and protection type (read-only or allow comments only). The default protection type is DocumentProtectionType.ReadOnly. The Document.IsDocumentProtected property indicates whether the document is protected.

Use the Document.Unprotect method to disable protection. Note that it unlocks the document without prompting the user for a password. To prompt the user with a password, execute the UnprotectDocumentCommand command.

NOTE

The RichEditDocumentServer protection affects only the document modification. The RichEditDocumentServer protection protects the document only against modifications. The document is opened without prompting for a password.

Grant Permission to Users

You can allow certain users to edit parts of a protected document by creating Range Permissions as described in the steps below.

  1. Call the SubDocument.BeginUpdateRangePermissions method to access the document range permissions collection.
  2. Create a new RangePermission object using the RangePermissionCollection.CreateRangePermission method.

  3. Utilize the RangePermission.UserName or RangePermission.Group property to specify the specific user or group of users that are allowed to edit the document range

    Make sure that the property value is equal to the target user’s credentials.

  4. Add the created object to the RangePermissionCollection.
    NOTE

    Users and groups range permissions are not compatible with Editing Restrictions in Microsoft Word. Only the predefined groups are saved in RTF format. Group names are not saved in DOC format.

  5. Finalize the modification by calling the SubDocument.EndUpdateRangePermissions method.
  6. Enable document protection. When the protection is enabled, ranges without editing permissions are read-only.

    server.LoadDocument("Documents//Grimm.docx", DocumentFormat.OpenXml);
    Document document = server.Document;
    
    // Protect document range
    RangePermissionCollection rangePermissions = document.BeginUpdateRangePermissions();
    RangePermission rp = rangePermissions.CreateRangePermission(document.Paragraphs[3].Range);
    rp.Group = "Everyone";
    rangePermissions.Add(rp);
    
    document.EndUpdateRangePermissions(rangePermissions);
    // Enforce protection and set password.
    document.Protect("123");