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

How do I get the first name and last name of the logged in Windows user?(如何获取已登录 Windows 用户的名字和姓氏?)
本文介绍了如何获取已登录 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 用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)