Forum Discussion

Atul Moghe's avatar
Atul Moghe
Brass Contributor
Aug 10, 2017
Solved

How to get user photo in C# using Graph API?

I am building a bot which shows user the searched user photo and other information. Rest of the information is being fetched properly other than user's photo.   I am trying to get user photo by usi...
  • Atul Moghe's avatar
    Nov 21, 2017

    I found the solution to this issue in one of the Richard diZerega's sample bots. Following is the way you display the user's photo in bot.

     

    Get the byte array of the user's photo by using Graph API.

     

    // Extension method
    public static async Task<byte[]> GetStreamWithAuthAsync(this HttpClient client, string accessToken, string endpoint)
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                using (var response = await client.GetAsync(endpoint))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var stream = await response.Content.ReadAsStreamAsync();
                        byte[] bytes = new byte[stream.Length];
                        stream.Read(bytes, 0, (int)stream.Length);
                        return bytes;
                    }
                    else
                        return null;
                }
            }

    Assign the above byte array with the prefix "data&colon;image/png;base64," and assign it to image URL property.

     

     

    // Get the users profile photo from the Microsoft Graph
    var bytes = await new HttpClient().GetStreamWithAuthAsync(token, "https://graph.microsoft.com/v1.0/me/photo/$value");
    var pic = "data&colon;image/png;base64," + Convert.ToBase64String(bytes);
    
    ThumbnailCard card = new ThumbnailCard()
     {
        Title = $"{((JValue)jItem["Subject"]).Value}",
        Subtitle = jItem.SelectToken("sender.emailAdress.name").ToString(),
        Text = jItem.SelectToken("body.content").ToString(),
        Images = new List<CardImage>()
        {
              new CardImage()
              {
                    Url= pic
              }
        }
     };
     return card;

     

     

     

Resources