How to: Programmatically search for a specific contact

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

This example searches an Outlook contacts folder for a specific contact by first and last name. The example assumes that a contact named John Evans exists in the contacts folder.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Example

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    FindContactEmailByName("John", "Evans");
}

private void FindContactEmailByName(string firstName, string lastName)
{
    Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI");
    Outlook.MAPIFolder contactsFolder =
        outlookNameSpace.GetDefaultFolder(
        Microsoft.Office.Interop.Outlook.
        OlDefaultFolders.olFolderContacts);

    Outlook.Items contactItems = contactsFolder.Items;

    try
    {
        Outlook.ContactItem contact =
            (Outlook.ContactItem)contactItems.
            Find(String.Format("[FirstName]='{0}' and "
            + "[LastName]='{1}'", firstName, lastName));
        if (contact != null)
        {
            contact.Display(true);
        }
        else
        {
            MessageBox.Show("The contact information was not found.");
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
Private Sub ThisAddIn_Startup(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles Me.Startup
    FindContactEmailByName("John", "Evans")
End Sub

Private Sub FindContactEmailByName(ByVal firstName As String, _
    ByVal lastName As String)
    Dim outlookNameSpace As Outlook.NameSpace = Me.Application.GetNamespace("MAPI")
    Dim contactFolder As Outlook.MAPIFolder = _
        outlookNameSpace.GetDefaultFolder( _
        Outlook.OlDefaultFolders.olFolderContacts)

    Dim contactItems As Outlook.Items = contactFolder.Items

    Try
        Dim contact As Outlook.ContactItem = _
            CType(contactItems.Find(String.Format _
            ("[FirstName]='{0}' and [LastName]={1}", _
            firstName, lastName)), Outlook.ContactItem)

        If contact IsNot Nothing Then
            contact.Display()
        Else
            MsgBox("The contact information was not found.")
        End If

    Catch ex As Exception
        Throw ex
    End Try
End Sub

See also