Set custom document properties with Word interop
You need to use CustomDocumentProperties
, not BuiltInDocumentProperties
. See MSDN reference on using Custom Document Properties in Word (and MSDN video here). You also need to check if the property exists and create it before trying to assign its value.
Core.DocumentProperties properties = (Core.DocumentProperties)this.Application.ActiveDocument.CustomDocumentProperties;
if (properties.Cast<DocumentProperty>().Where(c => c.Name == "DocumentID").Count() == 0)
properties.Add("DocumentID", false, MsoDocProperties.msoPropertyTypeString, Guid.NewGuid().ToString());
var docID = properties["DocumentID"].Value.ToString();
After asking the question in the MSDN forums, the answer was brought up. The problem is, that the way I tried was specific to VSTO. Due to my unknowing, I mixed up VSTO, Interop and other definitions, thus tagging this question wrong.
It now works using the following code:
logger.Info("Setting document properties");
object properties = doc.CustomDocumentProperties;
Type propertiesType = properties.GetType();
object[] documentCodeProperty = { "Codice_documento", false, Core.MsoDocProperties.msoPropertyTypeString, args[3] };
object[] documentVersionPoperty = { "Versione_documento", false, Core.MsoDocProperties.msoPropertyTypeString, args[4] };
propertiesType.InvokeMember("Add", BindingFlags.InvokeMethod, null, properties, documentCodeProperty);
propertiesType.InvokeMember("Add", BindingFlags.InvokeMethod, null, properties, documentVersionPoperty);