Reputation:
I can add a contact to a address book but for some reason I can't remove it. The code I'm executing is as follows.
String abName = "Name ofthe targetted address book";
Outlook.Folder addressBook;
if (targetFolder.Folders.OfType<Outlook.Folder>().Any(element
=> element.Name == abName))
addressBook = targetFolder.Folders[abName] as Outlook.Folder;
else
addressBook = targetFolder.Folders.Add(
abName, Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
addressBook.ShowAsOutlookAB = true;
for (int i = addressBook.Items.Count - 1; i >= 0; i--)
if (!stringList.Any(element
=> element == addressBook.Items.OfType<Outlook.ContactItem>()
.ToList()[i].Email1Address))
addressBook.Items.OfType<Outlook.ContactItem>().ToList().RemoveAt(i);
The fetching of the address book works and the matching for strings too. I get into the RemoveAt line for the exactly correct contacts. There's no error or other message when I execute the removal. Still, the contact list remain unaffected.
I suspect that I may be working on a copy of the actual list containing the contacts. The problem is that if I don't create a List, I'm not sure how to alter the list of contacts.
So, the most helpful answer would shed some light on how to alter addressBook
(or perhaps addressBook.Items
) given certain condition. E.g., say that we'd like to remove all the contants the name of whom starts with the letter "Q".
At this moment I can only think of a super ugly work-around and it's so rectum-ugly that I don't even mention it here. Really ugly...
Upvotes: 0
Views: 1527
Reputation: 96
Here is a solution
private void ClearContact(Outlook.Application outlookApplication)
{
Outlook.MAPIFolder contactFolder = outlookApplication.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
int total = contactFolder.Items.Count;
while (total > 0)
{
// first index number is 1 not 0
var contact = (Outlook.ContactItem)contactFolder.Items[1];
contact.Delete();
total = contactFolder.Items.Count;
}
}
I use netoffice outlook api http://netoffice.codeplex.com/wikipage?title=Outlook_Example05 And use while loop to delete all contact
Upvotes: 1
Reputation: 66306
You ae not removing an Outlook contact. You are removing an OUtlook object from your own List object.
You need to call ContactItem.Delete
.
As a side note, do not use multiple dot notation when working with COM objects, especially in a loop - you will receive a brand new COM object for each dot.
Upvotes: 1