Dat*_*ase 38 c# active-directory
如何在我的系统中使用c#获取我的名字姓氏(使用Active Directory用户名和密码登录Windows)?
是否有可能在不去AD的情况下做到这一点?
Jac*_*itt 56
如果您使用的是.Net 3.0或更高版本,那么有一个可爱的库可以实现这一点.System.DirectoryServices.AccountManagement有一个UserPrincipal对象可以得到你正在寻找的东西,你不必乱用LDAP或放弃系统调用来做到这一点.这就是它的全部内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您已经拥有用户名,则实际上并不需要主体,但如果您在用户上下文中运行,那么从那里开始就可以轻松实现.
小智 48
有一种更简单的方法可以做到这一点:
using System.DirectoryServices.AccountManagement;
UserPrincipal userPrincipal = UserPrincipal.Current;
String name = userPrincipal.DisplayName;
Run Code Online (Sandbox Code Playgroud)

这个解决方案对我不起作用,但这个功能很有用:
public static string GetUserFullName(string domain, string userName)
{
DirectoryEntry userEntry = new DirectoryEntry("WinNT://" + domain + "/" + userName + ",User");
return (string)userEntry.Properties["fullname"].Value;
}
Run Code Online (Sandbox Code Playgroud)
你应该这样称呼它:
GetUserFullName(Environment.UserDomainName, Environment.UserName);
Run Code Online (Sandbox Code Playgroud)
(在这里找到).
| 归档时间: |
|
| 查看次数: |
56593 次 |
| 最近记录: |