: 'Unable to cast COM object of type 'System.__ComObject' to interface type

0

I am getting the following error:

System.InvalidCastException: 'Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{00063034-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'

The code from which the error arises:

foreach (MailItem item in mailItems)
{
}
c#
asp.net
outlook
interop
asked on Stack Overflow Jan 11, 2018 by user2281858

1 Answer

0

It is possible that mailItems contains more objects other than Microsoft.Office.Interop.Outlook.MailItem as defined in the loop. The safest way is using object type to iterate mailItems, then check its type with as operator before running Outlook handler:

foreach (object item in mailItems)
{
    // try casting to Outlook.MailItem first
    var obj = item as Outlook.MailItem;

    // check if the conversion works and UnRead property can be accessed as well
    if (obj != null && obj.UnRead == true)
    {
        // do something
    }
    else
    {
        // do something else
    }
}
answered on Stack Overflow Jan 11, 2018 by Tetsuya Yamamoto • edited Jan 11, 2018 by Tetsuya Yamamoto

User contributions licensed under CC BY-SA 3.0