Search code examples
c#.net-coreazure-active-directoryazure-web-app-service

How Can I Update User Profile Image using Graph API in C#


I want to update my user Profile image and another user's profile Image using Graph API in C#.

I have all permission in Microsoft Azure to do anything using code.

How can it be done?


Solution

  • Make sure to grant User.ReadWrite.All application type API permission:

    enter image description here

    To update the profile photo of a user, please use the below code:

    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Azure.Identity;
    using Microsoft.Graph;
    
    namespace UserProperties
    {
        public class GraphHandler
        {
            public GraphServiceClient GraphClient { get; set; }
    
            public GraphHandler()
            {
                var tenantId = "TenantID";
                var clientId = "ClientID";
                var clientSecret = "ClientSecret";
                GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
            }
    
            public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
            {
                var options = new TokenCredentialOptions
                {
                    AuthorityHost = Azure.Identity.AzureAuthorityHosts.AzurePublicCloud
                };
    
                var clientSecretCredential = new Azure.Identity.ClientSecretCredential(tenantId, clientId, clientSecret, options);
                var scopes = new[] { "https://graph.microsoft.com/.default" };
    
                return new GraphServiceClient(clientSecretCredential, scopes);
            }
    
            public async Task<bool> UpdateProfilePicture(string userId, string imagePath)
            {
                try
                {
                    using (var stream = new FileStream(imagePath, FileMode.Open))
                    {
                        await GraphClient.Users[userId].Photo.Content.PutAsync(stream);
                        Console.WriteLine("Profile picture updated successfully.");
                        return true;
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error updating profile picture: {ex.Message}");
                    return false;
                }
            }
        }
    
        class Program
        {
            static async Task Main(string[] args)
            {
                var handler = new GraphHandler();
                var userId = "UserID"; // Replace with the desired user's ID
                await handler.UpdateProfilePicture(userId, "C:\\Users\\rukmini\\Downloads\\ruk.jpg");
            }
        }
    }
    

    enter image description here

    Profile photo updated successfully:

    enter image description here