我希望能够使用 Active Directory 中用户的显示名称来获取该用户的用户 ID。显示名称是从数据库中获取的,并且已在该用户会话期间使用以下代码来存储以获取显示名称:
using System.DirectoryServices.AccountManagement;
private string GetDisplayName()
{
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find currently logged in user
UserPrincipal user = UserPrincipal.Current;
return user.DisplayName;
}
这一次,我想要一个名为GetUserIdFromDisplayName()
返回 Active Directory 登录名。有任何想法吗?
我相信你可以通过使用内置功能比大卫的答案更容易做到这一点System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。
基本上,您可以定义域上下文并轻松在 AD 中查找用户和/或组:
using System.DirectoryServices.AccountManagement;
private string GetUserIdFromDisplayName(string displayName)
{
// set up domain context
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find user by display name
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, displayName);
//
if (user != null)
{
return user.SamAccountName;
// or maybe you need user.UserPrincipalName;
}
else
{
return string.Empty;
}
}
}
我认为没有必要去底层DirectoryEntry
对象,真的 - 除非没有任何属性UserPrincipal
确实是您正在寻找的。
PS:如果按显示名称搜索不起作用(我手边没有广告来测试它) - 您也可以随时使用PrincipalSearcher
找到您的用户:
using System.DirectoryServices.AccountManagement;
private string GetUserIdFromDisplayName(string displayName)
{
// set up domain context
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the display name passed in
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.DisplayName = displayName;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find match - if exists
UserPrincipal user = srch.FindOne() as UserPrincipal;
if (user != null)
{
return user.SamAccountName;
// or maybe you need user.UserPrincipalName;
}
else
{
return string.Empty;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)