Lock the header from editing on word document in C#

With the help of Spire.Doc, we can easily add and remove header on the word documents in C#. This article we will demonstrate how to lock down the header information from editing. We will divide it into two parts for the demo. Once is for locking the header information on the existing word document with header and the other is on the new creating word document.

How to lock the header information on the existing word document.

//Load the sample document with header
Document doc = new Document();
doc.LoadFromFile("sample.docx");

//Get the first section from the word document
Section section = doc.Sections[0];

//Protect the document and set the ProtectionType as AllowOnlyFormFields
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");

//Set the ProtectForm as false to unprotect the section
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

Effective screenshot of the header has been locked and the other area can be edited:

How to lock the header from editing on word document in C#

How to lock the header information for the new word document.

//Create a new instance of word document
Document doc = new Document();

//Add a section to the word document
Section section = doc.AddSection();

//Add header information to the section
HeaderFooter header = section.HeadersFooters.Header;
Paragraph HParagraph = header.AddParagraph();
TextRange HText = HParagraph.AppendText("Protect header");

//Add a paragraph to the section
Paragraph Para = section.AddParagraph();
Para.AppendText("Demo of how to lock the header information by Spire.Doc ");

//Set the ProtectionType as AllowOnlyFormFields and then unprotect the section
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

How to lock the header from editing on word document in C#