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

时间:2022-11-10
本文介绍了如何获取已登录 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 用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何确定用户帐户是启用还是禁用 下一篇:列出活动目录中的所有计算机

相关文章

最新文章