By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,871 Members | 2,337 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,871 IT Pros & Developers. It's quick & easy.

Looping through Contact Items in Outlook Throws Exceptions

P: 1
I have some code that loops through all contacts in a contact folder (approx 3000), reads some details from each contact and uses that information to perform various functions.

However, as the program loops through, reading each contact, it will randomly start throwing exceptions (usually a large batch at a time), therefore fails to read the contact. This is the current code snippet that I am using, although I have tried allsorts. I can't seem to get around some erratic (i.e. crap) behaviour from Outlook.

The exception thrown is "Specified cast is not valid" and occurs in the first statement in the "try" (well as you can see here, that is currently the ONLY statement in the "try" block!!).

I think it seems to think the object is an Outlook.__ComObject... or something like that..

Please can someone help, I am losing my hair here!! This is using Outlook 2003, developing with Visual Studio 2003 and C# .net!

Outlook.Application olApp = new Outlook.ApplicationClass();
Outlook.NameSpace NS = olApp.GetNamespace("mapi");
Outlook.MAPIFolder oContacts = NS.GetFolderFromID(ContactFolderEntryID,FolderStor eID);
Outlook.Items oItems = (Outlook.Items)oContacts.Items;
for(int i=1; i<=oItems.Count;i++)
Outlook.ContactItem oCt = (Outlook.ContactItem)oItems.GetNext();
/*string CustomerID = oCt.CustomerID;
if(Array.BinarySearch(UpdatedContactJustIDs,Custom erID)>=0)

//see if it is on OCRM
catch(Exception ex)
Apr 25 '07 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 638
Outlook.Items oItems = (Outlook.Items)oContacts.Items;
Outlook.ContactItem oCt = (Outlook.ContactItem)oItems.GetNext();
I would wager that not all the oContacts.Items can be cast to ContactItem, ie, they have the same inheritance (Outlook.Items) but are not ContactItem's.

I would do a type check first... instead of doing

Outlook.ContactItem oCT


object oCT

and then

oCT.GetType() == typeof(Outlook.ContactItem)

I believe that should work even for inherited items.

Run that check, then continue your code. If it fails, its not castable to ContactItem.
Apr 25 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.