得到logedin Windows用户名姓?用户名、logedin、Windows

2023-09-08 12:15:05 作者:海是倒过来的天#

我怎样才能在我的系统使用C#我的名字姓氏(登录窗口与Active Directory用户名和传)?

How I can get my first name last name with c# in my system (logging in windows with Active Directory username and pass)?

是否有可能做到这一点,而无需到AD?

Is it possible to do that without going to the AD?

推荐答案

如果您使用的是.NET 3.0或更高版本,有一个可爱的图书馆,使这个几乎自己写出来。 System.DirectoryServices.AccountManagement都有获得正是你所期待的一个UserPrincipal对象,你不必乱用LDAP或下降到系统调用来做到这一点。在这里,一切都这样可以把:

If you're using .Net 3.0 or higher, there's a lovely library that makes this practically write itself. 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. 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.