如何在我的系统中使用 c# 获取我的名字姓氏(使用 Active Directory 用户名和密码登录 Windows)?
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.
这篇关于如何获取已登录 Windows 用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!