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

-1

enter image description here

enter image description hereWhen I am a casting below code then i got an error

Code :

string subject = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[temp])
    .Subject.ToString();

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)).

c#
outlook
asked on Stack Overflow Nov 2, 2015 by ketannsolanki solanki • edited May 6, 2019 by Andrew Truckle

2 Answers

3

You need to check the item type first. Outlook folders may contain various types of items:

Object selObject = this.Application.ActiveExplorer().Selection[1];
        if (selObject is Outlook.MailItem)
        {
            Outlook.MailItem mailItem =
                (selObject as Outlook.MailItem);
            itemMessage = "The item is an e-mail message." +
                " The subject is " + mailItem.Subject + ".";
            mailItem.Display(false);
        }
        else if (selObject is Outlook.ContactItem)
        {
            Outlook.ContactItem contactItem =
                (selObject as Outlook.ContactItem);
            itemMessage = "The item is a contact." +
                " The full name is " + contactItem.Subject + ".";
            contactItem.Display(false);
        }
        else if (selObject is Outlook.AppointmentItem)
        {
            Outlook.AppointmentItem apptItem =
                (selObject as Outlook.AppointmentItem);
            itemMessage = "The item is an appointment." +
                " The subject is " + apptItem.Subject + ".";
        }
        else if (selObject is Outlook.TaskItem)
        {
            Outlook.TaskItem taskItem =
                (selObject as Outlook.TaskItem);
            itemMessage = "The item is a task. The body is "
                + taskItem.Body + ".";
        }
        else if (selObject is Outlook.MeetingItem)
        {
            Outlook.MeetingItem meetingItem =
                (selObject as Outlook.MeetingItem);
            itemMessage = "The item is a meeting item. " +
                 "The subject is " + meetingItem.Subject + ".";
        }

See How to: Programmatically Determine the Current Outlook Item for more information.

answered on Stack Overflow Nov 2, 2015 by Eugene Astafiev
0
string subject = myInbox.Items[temp])
    .Subject.ToString();

There is no need to cast frist check that myinbox object have subject property in not string then you need to cast it if it is string formate then don't need to cast it.

answered on Stack Overflow Nov 24, 2015 by ketannsolanki solanki • edited Nov 24, 2015 by Kamil Budziewski

User contributions licensed under CC BY-SA 3.0