如何使用 C# 中的 Graph API 更新用户个人资料图像

问题描述 投票:0回答:1

我想使用 C# 中的 Graph API 更新我的用户个人资料图像和另一个用户的个人资料图像。

我拥有 Microsoft Azure 中使用代码执行任何操作的所有权限。

怎么可能。

请向我推荐有关此问题的人

c# asp.net .net .net-core azure-web-app-service
1个回答
0
投票

确保授予

User.ReadWrite.All
应用程序类型API权限:

enter image description here

要更新用户的个人资料照片,请使用以下代码:

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

个人资料照片更新成功:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.