Search code examples
c#outlookadd-inoutlook-addin

Outlook - Search Routine Only Works In Debug Mode


I have a routine in C# to search for contacts in Outlook by filtering the Contact folder and it works when I debug it step by step, but if I let it run alone (without debug break) then it just do nothing, the results returned by Outlook are only empty arrays, no exception, nothing. This is the routine:

private List<Outlook.ContactItem> filterContactFolder(String searchStr, Outlook.Folder folder)
{
    List<Outlook.ContactItem> contacts = new List<Outlook.ContactItem>();

    string filter = "urn:schemas:contacts:fileas LIKE '%" + searchStr + "%'";
    Outlook.Search searchObject = null;
    String scope = String.Empty;
    try
    {
        scope = "'" + folder.FolderPath + "'";
        searchObject = Globals.ThisAddIn.Application.AdvancedSearch(scope, filter, false, Type.Missing);

        foreach (Outlook.ContactItem c in searchObject.Results)
        {
            contacts.Add(c);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    finally
    {
        if (searchObject != null) searchObject.ReleaseComObject();
    }

    return contacts;
}

Anybody has an idea of what is going on?


Solution

  • You try to get the results too early.

    The key fact is that the search is performed in another thread. You need to handle the AdvancedSearchComplete event of the Application class which is fired when the AdvancedSearch method has completed.

    You may find the Advanced search in Outlook programmatically: C#, VB.NET article helpful.