0
votes

Following code of my Microsoft Office WORD VSTO Add-in, was successfully getting the document title before. But now, it's throwing the error shown below:

string sTitle = oActiveDoc.BuiltInDocumentProperties["Title"].Value;

Error:

Cannot apply indexing with [] to an expression of type 'object'

Based on some similar online solutions (such as this and this) to the issue I tried the following code but I'm still getting the exact same error.

Question: What I may be missing here and how can it be resolved?

Ref: Document.BuiltInDocumentProperties gets a Microsoft.Office.Core.DocumentProperties collection that represents all the built-in document properties for the document.

Following also gives the exact same error:

string sTitle = oActiveDoc.BuiltInDocumentProperties["Title"].Value as string;

or

string sTitle = oActiveDoc.BuiltInDocumentProperties["Title"] as string;
3
what changed? is it running on a different machine? did your office version change?MikeJ
@MikeJ Since the above code has been working on my various VSTO projects since 2010, obviously the machines (XP, VISTA, Win10, etc.), the Visual Studio versions (2010,2012,2013,2015,2019) along with Office versions 92003/2007/2010/2016/O365 etc.) have changed, as well. And the same line of code worked on all those versions before. It seems from this post, the above code of line may not always be reliable.nam
sounds like you found the answer below but just out of curiosity have you tried to cast oActiveDoc.BuiltInDocumentProperties as Microsoft.Office.Core.DocumentProperties? does that fail? it sounds like the old PIAs you've originally built the project with no longer work with one of the newer versions of office. Late binding could be the safest route but I'm curious if .net detects the types are the same.MikeJ

3 Answers

1
votes

There are several ways to bridge the gap with exceptions you've got so far:

  1. Use dynamic and object references. Read more about this approach on the Read BuiltInDocumentProperties/CustomDocumentProperties alway null with Word 2010? page.

  2. Use the late-binding technology represented in .net framework by the Type.InvokeMember method.

0
votes

Try

string sTitle = oActiveDoc.BuiltInDocumentProperties.Item("Title").Value;
0
votes

could you try that:

         string sTitle;
         dynamic properties = oActiveDoc.BuiltInDocumentProperties;
         var property = properties["Title"];    
         if (property != null)
          {
              sTitle = property.Value.ToString();
          }