Exception occured when retrieving ContactItem from olFolderContact



I'm using the following code to try to retrieve ContactItems in Outlook:

Outlook.MAPIFolder defaultFolder = applicationObject.GetNamespace

foreach (Outlook.ContactItem item in defaultFolder.Items)

However, there are also DistListItem in the same folder and the following
exception occured:

System.InvalidCastException: Unable to cast COM object of type
'System._ComObject' to interface type
'Microsoflt.Office.Interop.Outlook.ContactItem'. This operation failed
because the QueryInterface call on the COM component for the interface with
IID ......

Is there another way other than 'foreach' clause that I can get the
ContactItem or DistListItem in a Outlook folder?



Ken Slovak - [MVP - Outlook]

There are a few ways to get around that problem.

One idea would be to get each item as a generic object and test for the
Class of the object using code like this:

Type _type;
_type = item.GetType();

object[] _args = new Object[] { };

Outlook.OlObjectClass _class =
(Outlook.OlObjectClass)_type.InvokeMember("Class", BindingFlags.Public |
BindingFlags.GetField | BindingFlags.GetProperty, null, item, _args);

If the item had Class == OlObjectClass.olContact it's the correct type and
you could cast the item to ContactItem.

Another idea would be to set up a restriction or filter on the Items
collection of the folder based on MessageClass. You can exclude all items
that have MessageClass <> "IPM.DistList" or an inclusive filter or
restriction using MessageClass == "IPM.Contact". Of course you would need to
have no custom message classes in the folder for that to work.

Whatever you do I'd put the code inside a try { } catch { } block.

Ivan K.

Ken Slovak - said:
There are a few ways to get around that problem.
One idea would be ...
Another idea would be ...

Ken, I'm afraid your ideas suggested just hide exception from user but they
don't allow to process outlook records properly. So, your advices cannot be
used even as workarounds.

Does anybody know why Outlook returns 'System._ComObject' instances instead
of expected Outlook.ContactItem ones? Is this a confirmed MS Outlook bug
(couldn't find a knowledge base article yet) or it can be a misuse of public
Outlook API (need a pattern or antipattern) ?




Dmitry Gusarov

I've solved this problem little bit easier:

var contact = contactItem as ContactItem;
if(contact != null)

or even more simply:
var contactItems = contacts.Items.OfType<ContactItem>();

Thanks for pointing out DistListItem, I've spent a half of hour before
understanding a problem.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question