X

在C#中获取微软用户名和用户头像(无需权限)

XFEstudio 2026-02-01 16:38 157
编辑于 2026-02-01 16:40

获取用户名

总体而言还算简单,只需要以下代码:

var userName = Environment.UserName;
Console.WriteLine(userName);

获取用户的头像

以下方法需要调用Win32的DLL,因此支持的站点仅为Windows

using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using System.Runtime.InteropServices;
using System.Text;

public static partial class UserTileHelper
{
    [DllImport("shell32.dll", EntryPoint = "#261",
               CharSet = CharSet.Unicode, PreserveSig = false)]
    public static extern void GetUserTilePath(string? username, uint whatever, StringBuilder picpath, int maxLength);

    public static string GetUserTilePath(string? username = null)
    {
        var sb = new StringBuilder(1000);
        GetUserTilePath(username, 0x80000000, sb, sb.Capacity);
        return sb.ToString();
    }

    public static ImageSource GetUserTile(string? username = null) => new BitmapImage(new Uri(GetUserTilePath(username)));
}

然后使用的时候只需要调用以下代码:

var userTile = UserTileHelper.GetUserTile();
0 条回复
暂无回复,快来抢沙发吧!
发表回复
登录 后发表回复。