Reputation: 685
I am trying to update existing custom properties programatically on a word .doc (word 97 - 2003). I initially solved with Aspose but due to limited licenses I can't use it for this project.
This code is taken wholesale from here with minor modifications for word instead of excel Accessing Excel Custom Document Properties programatically.
The first method works to add a custom property if it does not exist, the second can pull custom properties. I have not figured out how to update a property that already exists. I think it might have to do with the verb in InvokeMember() but I can't find much documentation.
public void SetDocumentProperty(string propertyName, string propertyValue)
{
object oDocCustomProps = oWordDoc.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
object[] oArgs = {propertyName,false,
MsoDocProperties.msoPropertyTypeString,
propertyValue};
typeDocCustomProps.InvokeMember("Add",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
oDocCustomProps,
oArgs);
}
public object GetDocumentProperty(string propertyName, MsoDocProperties type)
{
object returnVal = null;
object oDocCustomProps = oWordDoc.CustomDocumentProperties;
Type typeDocCustomProps = oDocCustomProps.GetType();
object returned = typeDocCustomProps.InvokeMember("Item",
BindingFlags.Default |
BindingFlags.GetProperty, null,
oDocCustomProps, new object[] { propertyName });
Type typeDocAuthorProp = returned.GetType();
returnVal = typeDocAuthorProp.InvokeMember("Value",
BindingFlags.Default |
BindingFlags.GetProperty,
null, returned,
new object[] { }).ToString();
return returnVal;
}
Upvotes: 2
Views: 3158
Reputation: 31
Don't know if you found the correct answer, but for anyone who visits this page looking to set an existing custom document property. It seems that you need to retrieve the document property first by using the BindingFlags.GetProperty
and then using BindingFlags.SetProperty
to set the value of the specific item retrieved.
You can also add some custom checking to determine that the object you are trying to set is valid.
public void SetDocumentProperty(string propertyName, object value)
{
// Get all the custom properties
object customProperties = wordDocument.CustomDocumentProperties;
Type customPropertiesType = customProperties.GetType();
// Retrieve the specific custom property item
object customPropertyItem = customPropertiesType.InvokeMember("Item",
BindingFlags.Default | BindingFlags.GetProperty, null, customProperties,
new object[] { propertyName });
Type propertyNameType = customPropertyItem.GetType();
// Set the value of the specific custom property item
propertyNameType.InvokeMember("Value", BindingFlags.Default | BindingFlags.SetProperty, null,
customPropertyItem, new object[] { value });
}
Upvotes: 3
Reputation: 1528
We normally retrieve all the props to a list and delete from document, change values and insert again. We use DSOFile.dll approach
Upvotes: 0