C# Reading Outlook Contacts
Read the default Outlook contacts folder from C# using the Outlook interop assembly and return them as a DataSet.
Here is sample code to read the contacts stored in Outlook.
- Add a reference to
Microsoft.Office.Interop.Outlook. - Add the using statement.
csharp
using Microsoft.Office.Interop.Outlook;
- Use this method. It returns the email address, first name and last name of every contact.
csharp
public DataSet GetContacts()
{
DataSet ds = new DataSet();
ds.Tables.Add("Contacts");
ds.Tables[0].Columns.Add("Email");
ds.Tables[0].Columns.Add("FirstName");
ds.Tables[0].Columns.Add("LastName");
Microsoft.Office.Interop.Outlook.Items OutlookItems;
Microsoft.Office.Interop.Outlook.Application outlookObj;
MAPIFolder Folder_Contacts;
outlookObj = new Microsoft.Office.Interop.Outlook.Application();
Folder_Contacts =
(MAPIFolder)outlookObj.Session.GetDefaultFolder(
OlDefaultFolders.olFolderContacts);
OutlookItems = Folder_Contacts.Items;
for (int i = 0; i < OutlookItems.Count; i++)
{
Microsoft.Office.Interop.Outlook.ContactItem contact =
(Microsoft.Office.Interop.Outlook.ContactItem)OutlookItems[i + 1];
DataRow dr = ds.Tables[0].NewRow();
dr[0] = contact.Email1Address;
dr[1] = contact.FirstName;
dr[2] = contact.LastName;
ds.Tables[0].Rows.Add(dr);
}
return ds;
}