Search code examples
c#automationoffice-interop

Using Late-Binding to Automate Word is throwing a MissingMemberException


i am trying to access some information from a running Microsoft Word application using the following code..

object appClass = Marshal.GetActiveObject("Word.Application");
object documents = appClass.GetType().GetProperty("Documents");
object count = documents.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, documents, null);

When i run this code it tells me that that Count was not found and has thrown a MissingMemberException.

Can anyone tell me what i am doing wrong?


Solution

  • You didn't get a reference to the Documents object, GetProperty returns a PropertyInfo. Fix:

            object appClass = Marshal.GetActiveObject("Word.Application");
            object documents = appClass.GetType().InvokeMember("Documents", BindingFlags.GetProperty, null, appClass, null);
            object count = documents.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, documents, null);
    

    Adding a reference to Microsoft.Office.Word.Interop can make this a lot less painful.