简体   繁体   中英

How to retrieve picture of a outlook contact

Microsoft.Office.Interop.Outlook.Items OutlookItems;
Microsoft.Office.Interop.Outlook.Application outlookObj = new Microsoft.Office.Interop.Outlook.Application();
MAPIFolder Folder_Contacts;
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];

    bool to = contact.HasPicture; //returns false although there is a picture in Outlook.
    string h = contact.FirstName; //returns my first name
}

Why is the above code not able to see the picture but can pull the first name and how can I get the picture.

Error:

在此处输入图片说明

在此处输入图片说明

Attachment.GetTemporaryFilePath Method (Outlook)

var attachment = contact.Attachments["ContactPicture.jpg"] as Attachment;
var path = attachment.GetTemporaryFilePath();

Attachment.SaveAsFile Method (Outlook)

var attachment = contact.Attachments["ContactPicture.jpg"] as Attachment;
attachment.SaveAsFile(savePath);

Note that "path" here includes the file name, not just the directory.

Example:

var savePath = @"C:\Users\User\Documents\OutlookPhotos\YourDesiredFileName.jpg";

Edit:

Here's a method. It handles nulls for you.

static void WriteOutlookContactPhotoToFile(ContactItem contact, string directory, string fileName)
{
    if (contact != null && contact.HasPicture)
    {
        var attachment = contact.Attachments["ContactPicture.jpg"] as Attachment;
        if (attachment != null)
        {
            string writePath = Path.Combine(directory, fileName);
            attachment.SaveAsFile(writePath);
        }
    }
}

In your screenshot above, ContactItem.HasPicture == false, which means there is no picture. The attachment is not guaranteed to be present. you need to check for null (attachment != null).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM