I am having great difficulty attempting to read emails out of my Default Inbox using Interop in C# .NET 6.0.
I have an application that currently utilizes Interop to read the users most recent emails from their Outlook, this application utilizes .NET Framework 4.8 and does not compile with any errors, but as a part of a a application I am currently developing, I am required to use the new .NET 6.0 SDK instead of .NET Framework.
The Code block I have taken from the .NET Framework 4.8 application is below: `
using Outlook = Microsoft.Office.Interop.Outlook;
private Outlook.Items ReturnOutlookEmails()
{
Outlook.Application oApp = new Outlook.Application();
var outlookVersionString = oApp.Version;
Debug.WriteLine(oApp.Session);
Outlook.NameSpace oNS = oApp.GetNamespace("MAPI");
Outlook.MAPIFolder inbox = oNS.GetDefaultFolder(
Outlook.OlDefaultFolders.olFolderInbox);
//Get the Items collection in the Inbox folder.
Outlook.Items emails = inbox.Items;
return emails;
}
The error that is being thrown is of type "System.InvalidCastException", but if you look below that, it seems the real issue relates to an issue importing a COM component.
"System.InvalidCastException: 'Unable to cast COM object of type 'Microsoft.Office.Interop.Outlook.ApplicationClass' to interface type 'Microsoft.Office.Interop.Outlook._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063001-0000-0000-C000-000000000046}' failed due to the following error: Error loading type library/DLL. (0x80029C4A (TYPE_E_CANTLOADLIBRARY)).'"
The COM Component it is failing to import is the Microsoft Outlook 16.0 Object Library, I know this due to the fact that when I attempt to import the Library VIA the Dependencies Manager within the Project it does not correctly import, and shows the COM IID.
Image of Microsoft Outlook COM Library
I have tried many different ways to fix this error, but it seems whatever I try fails. I have attempted install the Microsoft.Office.Interop.Outlook.dll from NuGet, but this gives me a different issue, and stops this Method from running at all.
The Error found when using the package from NuGet can be found below:
System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'
I am completely stumped at this point, and I am struggling to find a way to fix this issue, if anyone knows a way to fix this, or somehow workaround this issue, such as the creation of a .NET Standard Class Library that integrates with my .NET 6.0 application, that would be awesome!
Thankyou in advance!