I have written some code to add custom fields to a Word document template based on the information in How do I add custom properties to a Word doc with .NET 4?
It works but it throws an exception if the field already exists. I would therefore like to read the existing custom fields to check what is already there.
I wrote a function based on the information at http://msdn.microsoft.com/en-us/library/dhxe2d75(v=vs.110).aspx
but it crashes on the first iteration of the foreach loop.
If there are no custom properties it does not throw an exception.
What am I doing wrong?
A first chance exception of type 'System.InvalidCastException' occurred in Unknown Module. Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Core.DocumentProperty'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{2DF8D04E-5BFA-101B-BDE5-00AA0044DE52}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
private bool PropertyExists(Word.Document Document, string PropertyName)
{
bool _bRet = false;
foreach (Microsoft.Office.Core.DocumentProperty _property in Document.CustomDocumentProperties)
{
if (_property.Name == PropertyName)
{
_bRet = true;
}
}
return _bRet;
}