代码之家  ›  专栏  ›  技术社区  ›  Ashish Prajapati

如何在C中使用Graph API更新用户配置文件图像#

  •  0
  • Ashish Prajapati  · 技术社区  · 1 年前

    我想使用C#中的Graph API更新我的用户配置文件映像和另一个用户的配置文件映像。

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

    这怎么可能呢。

    请给我推荐一个关于这个的人

    1 回复  |  直到 1 年前
        1
  •  1
  •   Rukmini    1 年前

    确保授予 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

    推荐文章