C# Marshal.GetActiveObject() alternative for Outlook Automation on .NET 5.0

Viewed 1300

I'm going to start a new project for Outlook interaction from external application (mail subject manipulation, clearing subject from Re: Fw: etc.. add subject tags, research subject tags in external DB etc..). I'm used to call Marshall.GetActiveObject() method to take control of already running Outlook Application.

With the release of .NET 5.0 I discovered that Marshall.GetActiveObject() method is no more available.

Is there an alternative way to do that? I want to use .NET 5.0 instead of .NET Framework in order to avoid any further problem with .NET Framework deprecations.

Thanks in advance, brgds.

2 Answers

Outlook is a singleton - there is always only one instance of outlook.exe running. There is absolutely no reason to use Marshall.GetActiveObject() - always create a new instance of the Outlook.Application object using the new operator.

If it helps any, I am in the same boat - trying to port Outlook Interop code to NET 5 but without using GetActiveObject("Outlook.Application") as Outlook.Application; to get a reference to the running Outlook app. My NET Framework 4.8 code worked fine for a couple of years, so of course it is (was) possible to use GetActiveObject for the job.

But with NET 5, I am struggling to find a way to reference the Office apps. I show code below that works with Outlook (even though it should not, I think).

NET 4.8 (works)
var o = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;

NET 5.0 (works)
var o = Marshal.BindToMoniker("Outlook.Application") as Outlook.Application;

I don't know why BindToMoniker works - I thought it took a pathname as an argument. Anyhow, it works for me on Windows11 NET 5.0 with project TargetFramework and Interop.Outlook reference shown below.

<PropertyGroup>
        <TargetFramework>net5.0-windows</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
      <COMReference Include="Microsoft.Office.Interop.Outlook">

I am still stuck on how to get references to running Office apps for Excel, Access, Word, etc.

UPDATE Charlieface provided a link for me to the solution, which was to create my own Marshal2.GetActiveObject interface as shown in this post:

How to connect an open excel application in net.core 3.1?

Related