问题描述
如何在我的系统中使用 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 用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)