获取Windows用户显示名称的可靠方法

我需要获取当前用户的显示名称,并且找不到始终有效的解决方案。 为了清楚起见,我不在寻找用户名。 我需要“John Doe”。 开始菜单上显示的值。

有很多关于这个问题的帖子,但没有解决我的问题。

获取Windows用户显示名称

如何获取当前登录用户的AD显示名称

这两个帖子引导我:

PrincipalContext context = domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase) ?
    new PrincipalContext(ContextType.Machine) :
    new PrincipalContext(ContextType.Domain, domain);

UserPrincipal userPrincipal = new UserPrincipal(context) { SamAccountName = username };
PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);
userPrincipal = searcher.FindOne() as UserPrincipal;

string displayName = userPrincipal.DisplayName;

而这个代码大部分工作。 但是,如果用户已禁用/停止他/她的计算机上的服务器服务,则会收到一条异常,指出“服务器服务未启动。”

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

同样的错误。

如何在Windows中获取登录用户的全名?

StringBuilder name = new StringBuilder(1024);
uint userNameSize = (uint)name.Capacity;
const int NameDisplay = 3;
GetUserNameEx(NameDisplay, name, ref userNameSize)

如果用户不在域中,则返回没有错误,但为空字符串。

如何可靠地在所有版本的Windows上读取用户的显示(第一个和最后一个)名称?

// get SAM compatible name <server/machine><username>
if (0 != GetUserNameEx(2, username, ref userNameSize))
{
    IntPtr bufPtr;
    try
    {
        string domain = Regex.Replace(username.ToString(), @"(.+).+", @"$1");
        DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
        DomainController dc = DomainController.FindOne(context);

        if (0 == NetUserGetInfo(dc.IPAddress,
                   Regex.Replace(username.ToString(), @".+(.+)", "$1"),
                   10, out bufPtr))
        {
            var userInfo = (USER_INFO_10) Marshal.PtrToStructure(bufPtr, typeof (USER_INFO_10));
            return Regex.Replace(userInfo.usri10_full_name, @"(S+), (S+)", "$2 $1");
        }
    }
    finally
    {
        NetApiBufferFree(out bufPtr);
    }
}

通过上面的介绍,当DomainController.FindOne被调用时,我得到一个ActiveDirectoryObjectNotFoundException异常消息“域中找不到域控制器..”。

我还没有找到显示名称的注册表设置。

我不知道还有什么可以尝试的。 请帮忙。


以上所有方法只适用于您在域中的用户。 如果您不是,那么您必须依靠本地用户帐户存储。 以下详细说明如何检索此信息:如何获取本地Windows用户(仅显示在Windows登录屏幕中的用户)列表。 但在域名情况下,用户帐户将不在本地商店中。

如果您位于域中但未连接到域控制器,则显示名称将不会随时为您提供。 此信息存储在域控制器上,而不是本地用户的计算机上。 如果你的用户在一个域上,他们真的不应该能够禁用服务器服务(使用GPO)。 另外,它们失去的功能远远超过通过禁用该服务来检索其用户帐户的能力。

在尝试获取显示名称之前,我会检查域的可用性。 如果失败,则显示指示失败的消息。 这里可能有太多的边界案例来解决所有这些问题。 按照您打算使用该程序的方案进行操作,并为其他人提供错误消息。

链接地址: http://www.djcxy.com/p/83171.html

上一篇: A reliable way to obtain the Windows user display name

下一篇: Should one call Dispose for Process.GetCurrentProcess()?