Konrad Viltersten
Konrad Viltersten

Reputation: 39058

Determine if an address book exists in Outlook 2010

I've created an address book as described here and that works like a charm. Then I'd like to access it - first checking if it exists (and creating it in the opposite case), then referencing it.

My current code is relying on an Exception to detect missing name folder, which, in my view, is an ugly work-around. I haven't found a neater method, like e.g. .DoesFolderExist or such. I'd like to get an suggestion on how to improve it.

Outlook.Folder contacts = 
  this.Application.Session.GetDefaultFolder(
    Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
Outlook.Folder addressBook = null;

try { addressBook = contacts.Folders["My AB"] as Outlook.Folder; }
catch (Exception) { }

if (addressBook == null)
{
    addressBook = contacts.Folders.Add("My AB", 
      Outlook.OlDefaultFolders.olFolderContacts) as Outlook.Folder;
    addressBook.ShowAsOutlookAB = true;
}

Should I be using this.Application.Session.GetFolderFromID(...) instead? The problem there is that I need to specify both the name of the address book (which I have) and a store id (which I don't have). I prefer not to go there but the syntax of the method GetFolderFromID suggests that there could be two different address books with equal names but placed in different stores. Is it so or does contact.Folder["name"] above suffice?

Upvotes: 2

Views: 895

Answers (1)

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31641

You can use the try/catch-statement approach, but a better one is to iterate through each Folder to avoid the exception and performance hit.

Outlook.Folders contactFolders = contacts.Folders;
if (contactFolders.Cast<Outlook.Folder>()
  .Where(c => c.Name == "My AB").Count() > 0)
    addressBook = contactFolders["My AB"] as Outlook.Folder;

Upvotes: 3

Related Questions