我使用 System.DirectoryServices.AccountManagement
查询 Active Directory 以获取单个用户信息
public UserInfo FindOne(string samUserName)
{
using (var ctx = new PrincipalContext(ContextType.Domain, "domain.com", "Bob", "pwd"))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, samUserName))
{
if (user != null)
{
// get info about Alice into userInfo
return userInfo;
}
}
}
return null;
}
因此,如果我使用 var aliceInfo = search.FindOne("alice");
,我会从目录中获取信息。现在我需要搜索给定多个用户登录名的目录(1000 多个用户),例如
var userInfos = search.FindMany(/* list of names: alice, jay, harry*/);
如何实现下面的方法?
public List<UserInfo> FindMany(List<string> samUserNames)
{
...
}
最佳答案
试试这个:
string query = "dc=com,dc=domainController,ou=Users"; //this is just an example query, change it to suit your needs
// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourDomain", query);
// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
return srch.FindAll().Select(p => p as UserPrincipal);
这样你就可以从AD中返回所有的用户,然后过滤掉那些你不需要的。 UserPrincipal 有一些与用户相关的属性,例如 Surname 和 Sid,但是如果您需要获取 UserPrincipal 没有的值,您可以创建一个扩展方法并访问任何 LDAP 属性:
public static String GetProperty(this Principal principal, String property)
{
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
if (directoryEntry.Properties.Contains(property))
return directoryEntry.Properties[property].Value.ToString() ?? "";
else
return String.Empty;
}
这是 LDAP 属性的列表:https://fsuid.fsu.edu/admin/lib/WinADLDAPAttributes.html
关于c# - 如何在给定多个用户名的情况下查询 Active Directory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814371/