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

How can I update user Profile Photo using UPN(User Principal Name) using Graph API in C#


I tried with UserID and that is works perfect but when I am trying with userPrincipalName then it is not working.

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 (ODataError odataError)
    {
        Console.WriteLine($"OData error details:");
        Console.WriteLine($"Code: {odataError.Error?.Code}");
        Console.WriteLine($"Message: {odataError.Error?.Message}");
        throw;
    }
    catch (ServiceException ex)
    {
        Console.WriteLine($"Error updating profile picture: {ex.Message}");
        return false;
    }
}

Error Image

If I tried with userPrincipalName then is it not works.


Solution

  • Initially I got the same error:

    enter image description here

    To resolve the error to update profile photo of user by passing UPN, you need to get user by UPN by passing below code snippet:

    Var user = await GraphClient.Users[userPrincipalName].GetAsync();
    

    To update the user's profile picture by passing UPN, modify the code like below:

    using Azure.Identity;
    using Microsoft.Graph;
    using Microsoft.Graph.Models.ODataErrors;
    
    namespace UserProperties
    {
        public class GraphHandler
        {
            public GraphServiceClient GraphClient { get; set; }
    
            public GraphHandler()
            {
                var tenantId = "XXX";
                var clientId = "XXX";
                var clientSecret = "XXX";
                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> UpdateProfilePictureByUPN(string userPrincipalName, string imagePath)
            {
                try
                {
                    using (var stream = new FileStream(imagePath, FileMode.Open))
                    {
                        // Get user by UPN
                        var user = await GraphClient.Users[userPrincipalName].GetAsync();
                        if (user != null)
                        {
                            // Update profile picture
                            await GraphClient.Users[user.Id].Photo.Content.PutAsync(stream);
                            Console.WriteLine("Profile picture updated successfully.");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"User with UPN '{userPrincipalName}' not found.");
                            return false;
                        }
                    }
                }
                catch (ODataError odataError)
                {
                    Console.WriteLine($"OData error details:");
                    Console.WriteLine($"Code: {odataError.Error?.Code}");
                    Console.WriteLine($"Message: {odataError.Error?.Message}");
                    throw;
                }
                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 userPrincipalName = "[email protected]"; // Replace with the desired user's UPN
                await handler.UpdateProfilePictureByUPN(userPrincipalName, "C:\\Users\\rukmini\\Downloads\\ruk.jpg");
            }
        }
    }
    

    enter image description here

    The profile picture updated successfully like below:

    enter image description here