How do I get the first name and last name of the logged in Windows user?(如何获取已登录 Windows 用户的名字和姓氏?)
问题描述
如何在我的系统中使用 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 用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取已登录 Windows 用户的名字和姓氏?
基础教程推荐
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- 创建属性设置器委托 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01