简体   繁体   English

如何获得已登录Windows用户的名字和姓氏?

[英]How do I get the first name and last name of the logged in Windows user?

How I can get my first name last name with c# in my system (logging in windows with Active Directory username and pass)? 如何在系统中使用c#获取我的姓氏(使用Active Directory用户名登录并通过Windows)?

Is it possible to do that without going to the AD? 是否可以不通过广告就这样做?

If you're using .Net 3.0 or higher, there's a lovely library that makes this practically write itself. 如果您使用的是.Net 3.0或更高版本,则有一个可爱的库可以使它自己编写。 System.DirectoryServices.AccountManagement has a UserPrincipal object that gets exactly what you are looking for and you don't have to mess with LDAP or drop to system calls to do it. System.DirectoryServices.AccountManagement具有一个UserPrincipal对象,该对象可以准确获取您要查找的内容,而您无需弄乱LDAP或直接进行系统调用即可。 Here's all it'd take: 这就是全部:

Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
// or, if you're in Asp.Net with windows authentication you can use:
// WindowsPrincipal principal = (WindowsPrincipal)User;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
    return up.DisplayName;
    // or return up.GivenName + " " + up.Surname;
}

Note: you don't actually need the principal if you already have the username, but if you're running under the users context, it's just as easy to pull it from there. 注意:如果已经有了用户名,则实际上不需要主体,但是如果在用户上下文中运行,从那里拉取它就很容易。

There is an easier way to do this: 有一个更简单的方法可以做到这一点:

using System.DirectoryServices.AccountManagement;

UserPrincipal userPrincipal = UserPrincipal.Current;
String name = userPrincipal.DisplayName;

在此处输入图片说明

This solution didn't work for me but this function worked great: 这个解决方案对我不起作用,但是这个功能很好用:

public static string GetUserFullName(string domain, string userName)
        {
            DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
            return (string)userEntry.Properties["fullname"].Value;
        }

You should call it that way: 您应该这样称呼:

GetUserFullName(Environment.UserDomainName, Environment.UserName);

(Found it here ). 在这里找到)。

The problem with the approved answer is that if you have a policy of Lastname, Firstname in place, then DisplayName gives Smith, John, not John Smith. 批准的答案的问题在于,如果您具有“姓氏,名字”策略,则DisplayName会给Smith,John而不是John Smith。 There are two ways to get the correct form, the userPrincipal.Name property contains "John Smith (jsmith1)" so you could use this, and just string.Split on "(". Or use the following: 有两种获取正确格式的方法,userPrincipal.Name属性包含“ John Smith(jsmith1)”,因此您可以使用它,而只是将string.Split放在“(”上。或者使用以下方法:

private string ConvertUserNameToDisplayName(string currentSentencedByUsername)
    {
        string name = "";
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            var usr = UserPrincipal.FindByIdentity(context, currentSentencedByUsername);
            if (usr != null)
                name = usr.GivenName+" "+usr.Surname;
        }
        if (name == "")
            throw new Exception("The UserId is not present in Active Directory");
        return name;
    }

This would give the required form "John Smith" as required by the original poster. 这将提供原始海报所需的“ John Smith”表格。

The fastest way is to bind directly to their AD object using their SID, which you already have. 最快的方法是使用已经拥有的SID直接绑定到其AD对象。 For example: 例如:

//ASP.NET
var identity = (WindowsIdentity) HttpContext.Current.User.Identity;

//Desktop
var identity = WindowsIdentity.GetCurrent();

var user = new DirectoryEntry($"LDAP://<SID={identity.User.Value}>");

//Ask for only the attributes you want to read.
//If you omit this, it will end up getting every attribute with a value,
//which is unnecessary.
user.RefreshCache(new [] { "givenName", "sn" });

var firstName = user.Properties["givenName"].Value;
var lastName = user.Properties["sn"].Value;

Had the same issue. 有同样的问题。 After some research and browsing the Microsoft Docs, I found the solution. 经过研究并浏览了Microsoft Docs,我找到了解决方案。

First install the System.DirectoryServices.AccountManagement package using Nuget Package Manager. 首先使用Nuget软件包管理器安装System.DirectoryServices.AccountManagement软件包。

Then while calling the GetUserNameWithoutDomain method pass the following as the parameters: 然后,在调用GetUserNameWithoutDomain方法时,将以下内容作为参数传递:

GetUserNameWithoutDomain(UserPrincipal.Current.GivenName, UserPrincipal.Current.Surname); This should definitely work! 这绝对应该工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM