Home > OS >  Late Binding Interop libraries for usage on multiple systems with c#
Late Binding Interop libraries for usage on multiple systems with c#

Time:11-28

I am trying to write an application that can load the correct Interop office library and retrieve information about the application. I have been trying to do this with word.

Type wordType = Type.GetTypeFromProgID("Word.Application");
dynamic word = Activator.CreateInstance(wordType);

Console.WriteLine(word.Application.ActiveWindow.Document.FullName);

I have a word document open but I cannot access the window. It throws an error

System.Runtime.InteropServices.COMException (0x800A1098): Dieser Befehl ist nicht verfügbar, weil kein Dokument geöffnet ist.

Which is translated to no Document is availabe.

However if I do not use late binding

var word = (Microsoft.Office.Interop.Word.Application)Marshal2.GetActiveObject("Word.Application");
Console.WriteLine(word.Application.ActiveWindow.Document.FullName);

I can read the document file...

If I cannot use late binding I have to compile the interop and ship it with the application. My goal would be that it uses the interop of the programs that are installed, if they are installed.

How can I connect to the correct instance and read informations about the active window?

CodePudding user response:

Apples and oranges by the way. In the first example you are spawning a new instance of the Word application (without any documents I might add), and the second is using IROT for an existing Word app that no doubt has a document and therefore active.


In your first scenario, you merely spawned a new instance of a Word but did not create a document. Like most Office applications, Word starts with no documents by default.

Change:

Type wordType = Type.GetTypeFromProgID("Word.Application");
dynamic word = Activator.CreateInstance(wordType);

Console.WriteLine(word.Application.ActiveWindow.Document.FullName);

...to:

var wordType = Type.GetTypeFromProgID("Word.Application");
dynamic app = Activator.CreateInstance(wordType);
dynamic doc = app.Documents.Add(); // <---- the important bit

Console.WriteLine(doc.FullName);

See also

  • Related