I am manipulating a Word 2010 document on the server-side and some of the content controls in the document have the following Locking properties checked
Can anyone advise set these Locking options to false or remove then altogether using the OpenXML SDK?
Quick guide: unlocking a Word document You'll need the password to unprotect your documents as well: In Word versions 2019 to 2010 and Microsoft 365, enter the password to unlock Word under "File" > "Protect Document" > "Restrict Editing" and then click "Stop Protection".
Press Ctrl+A to select the entire document. Right-click a visible content control. In the context menu, click Remove Content Control.
Select the field you want to unlock. Press Ctrl+Shift+F11.
The openxml SDK provides the Lock
class and the LockingValues
enumeration
for programmatically setting the options:
So, to set those two options to "false" (LockingValues.Unlocked
),
search for all SdtElement
elements in the document and set the Val
property to
LockingValues.Unlocked
.
The code below shows an example:
static void UnlockAllSdtContentElements()
{
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open(@"c:\temp\myword.docx", true))
{
IEnumerable<SdtElement> elements =
wordDoc.MainDocumentPart.Document.Descendants<SdtElement>();
foreach (SdtElement elem in elements)
{
if (elem.SdtProperties != null)
{
Lock l = elem.SdtProperties.ChildElements.First<Lock>();
if (l == null)
{
continue;
}
if (l.Val == LockingValues.SdtContentLocked)
{
Console.Out.WriteLine("Unlock content element...");
l.Val = LockingValues.Unlocked;
}
}
}
}
}
static void Main(string[] args)
{
UnlockAllSdtContentElements();
}
Just for the ones who copy this code, keep in mind that if there is no Locks associated to the content control, then there won't be a Lock property associated to it, so when the code executes the following instruction, it will return a exception since there is no element found:
Lock l = elem.SdtProperties.ChildElements.First<Lock>();
The way to fix this is do the FirstOrDefault
instead of First
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With