我想使用 C# 中的 Graph API 更新我的用户个人资料图像和另一个用户的个人资料图像。
我拥有 Microsoft Azure 中使用代码执行任何操作的所有权限。
怎么可能。
请向我推荐有关此问题的人
确保授予
User.ReadWrite.All
应用程序类型API权限:
要更新用户的个人资料照片,请使用以下代码:
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");
}
}
}
个人资料照片更新成功: