Sam
Sam

Reputation: 29009

How to get all contacts in Exchange Web Service (not just the first few hundreds)

I'm using Exchange Web Service to iterate through the contacts like this:

ItemView view = new ItemView(500);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);
FindItemsResults<Item> findResults = _service.FindItems(WellKnownFolderName.Contacts, view);
foreach (Contact item in findResults.Items)
{
  [...]
}

Now this restricts the result set to the first 500 contacts - how do I get the next 500? Is there some kind of paging possible? Of course I could set 1000 as Limit. But what if there are 10000? Or 100000? Or even more?

Upvotes: 2

Views: 1354

Answers (1)

Jan Doggen
Jan Doggen

Reputation: 9096

You can do 'paged search' as explained here.

FindItemsResults contains a MoreAvailable probably that will tell you when you're done.

The basic code looks like this:

while (MoreItems)
{
// Write out the page number.
Console.WriteLine("Page: " + offset / pageSize);

// Set the ItemView with the page size, offset, and result set ordering instructions.
ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);
view.OrderBy.Add(ContactSchema.DisplayName, SortDirection.Ascending);

// Send the search request and get the search results.
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Contacts, view);

// Process each item.
foreach (Item myItem in findResults.Items)
{
    if (myItem is Contact)
    {
        Console.WriteLine("Contact name: " + (myItem as Contact).DisplayName);
    }
    else
    {
        Console.WriteLine("Non-contact item found.");
    }
}

// Set the flag to discontinue paging.
if (!findResults.MoreAvailable)
    MoreItems = false;

// Update the offset if there are more items to page.
if (MoreItems)
    offset += pageSize;
}   

Upvotes: 3

Related Questions