如何检索Outlook联系人的图片

时间:2016-03-09 21:41:32

标签: c# outlook

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
}

为什么上面的代码无法看到图片,但可以拉出名字,我怎样才能得到图片。

错误:

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

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);

请注意,此处的“路径”包括文件名,而不仅仅是目录。

示例:

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

修改

这是一种方法。它为你处理空值。

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);
        }
    }
}

答案 1 :(得分:0)

在上面的屏幕截图中,ContactItem.HasPicture == false,表示没有图片。不保证附件存在。你需要检查null(attachment!= null)。