You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7.0(C#)获取Windows域用户姓名遇异常求替代方案

在.NET 7 Windows项目中获取AD用户真实姓名的替代方案

方法1:调用Windows原生API(最稳定)

直接通过P/Invoke调用系统API,无需额外NuGet包,兼容性拉满:

using System;
using System.Runtime.InteropServices;
using System.Text;

public static class UserDisplayNameHelper
{
    private enum ExtendedNameFormat
    {
        NameDisplay = 3
    }

    [DllImport("secur32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool GetUserNameEx(ExtendedNameFormat format, StringBuilder buffer, ref uint bufferSize);

    public static string GetCurrentUserDisplayName()
    {
        uint bufferSize = 0;
        // 先获取所需缓冲区大小
        GetUserNameEx(ExtendedNameFormat.NameDisplay, null, ref bufferSize);
        if (bufferSize == 0)
            throw new System.ComponentModel.Win32Exception();

        var nameBuffer = new StringBuilder((int)bufferSize);
        if (!GetUserNameEx(ExtendedNameFormat.NameDisplay, nameBuffer, ref bufferSize))
            throw new System.ComponentModel.Win32Exception();

        return nameBuffer.ToString();
    }
}

调用方式:var displayName = UserDisplayNameHelper.GetCurrentUserDisplayName();

方法2:直接查询Active Directory

如果需要查询特定用户(而非当前登录用户),先安装NuGet包System.DirectoryServices,再用以下代码:

using System.DirectoryServices;

public static string GetUserDisplayNameFromAD(string domainUser)
{
    var domainAndUser = domainUser.Split('\\');
    var domain = domainAndUser[0];
    var userName = domainAndUser[1];

    using var adEntry = new DirectoryEntry($"LDAP://{domain}");
    using var searcher = new DirectorySearcher(adEntry)
    {
        Filter = $"(&(objectClass=user)(sAMAccountName={userName}))",
        PropertiesToLoad = { "displayName" }
    };

    var result = searcher.FindOne();
    return result?.Properties["displayName"]?[0]?.ToString();
}

调用示例:var displayName = GetUserDisplayNameFromAD("DomainXX\\U12312");

方法3:兼容AccountManagement的 fallback方案

如果想保留原思路,可加异常捕获,失败时自动切换到原生API:

using System.DirectoryServices.AccountManagement;

public static string GetUserDisplayName()
{
    try
    {
        using var context = new PrincipalContext(ContextType.Domain);
        using var user = UserPrincipal.Current;
        return user.DisplayName;
    }
    catch (PlatformNotSupportedException)
    {
        // 失败时切换到原生API
        return UserDisplayNameHelper.GetCurrentUserDisplayName();
    }
}

内容的提问来源于stack exchange,提问作者Sonderwoods

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:45:56