Hi @Aaron Gerber ,
The custom file properties are stored in the CustomFilePropertiesPart
of the document. You can access this part through the MainDocumentPart
.
If the CustomFilePropertiesPart
does not exist, you will need to create it before you can add or modify properties.
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.CustomProperties
Imports DocumentFormat.OpenXml.VariantTypes
Sub ModifyCustomProperties(docPath As String)
Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(docPath, True)
Dim customPropsPart As CustomFilePropertiesPart = wordDoc.CustomFilePropertiesPart
If customPropsPart Is Nothing Then
customPropsPart = wordDoc.AddCustomFilePropertiesPart()
' Add initial properties if needed
customPropsPart.Properties = New Properties()
End If
Dim properties = customPropsPart.Properties
' Check if a property exists by name
Dim existingProp = properties.OfType(Of CustomDocumentProperty)().
FirstOrDefault(Function(p) p.Name.Value = "YourPropertyName")
If existingProp IsNot Nothing Then
existingProp.VTLPWSTR.Text = "NewValue"
Else
Dim newPropId = If(properties.Elements(Of CustomDocumentProperty).Any(),
properties.Elements(Of CustomDocumentProperty).Max(Function(p) CInt(p.PropertyId.Value)) + 1,
1)
Dim newProp = New CustomDocumentProperty() With {
.Name = "YourPropertyName",
.PropertyId = newPropId,
.VTLPWSTR = New VTLPWSTR("YourValue")
}
properties.AppendChild(newProp)
End If
customPropsPart.Properties.Save()
End Using
End Sub
Best Regards.
Jiachen Li
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.