我尝试使用 UserID ,效果很完美,但是当我尝试使用 userPrincipalName 时,它不起作用。
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;
}
}
如果我尝试使用 userPrincipalName 那么它不起作用。
最初我遇到了同样的错误:
要解决更新用户个人资料照片的错误,您需要通过传递以下代码片段通过 UPN 获取用户:
Var user = await GraphClient.Users[userPrincipalName].GetAsync();
要通过UPN更新用户的个人资料图片,请修改如下代码:
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");
}
}
}
头像更新成功如下: