如何获得已登录Windows用户的名字和姓氏? [英] How do I get the first name and last name of the logged in Windows user?

查看:155
本文介绍了如何获得已登录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)?

是否可以做到这一点?

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用户的名字和姓氏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆