0

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;
    }
Community
  • 1
  • 1
cm5053
  • 18
  • 5
  • Do you think this has been adequately answered over in http://social.msdn.microsoft.com/Forums/office/en-US/4dfeb382-8c23-40e0-8f6e-e17c016476fe/pass-a-message-or-set-a-property-from-windows-form-to-word-document?forum=worddev ? –  Sep 10 '14 at 06:48
  • Thank you for your reply. Unfortunately the link does not help much. I tried to use the function `ReadDocumentProperty` but it throws an exception on the line `properties = myWordDoc.CustomDocumentProperties;` It's really the same problem as before. – cm5053 Sep 10 '14 at 18:09

0 Answers0