C# 如何从Active Directory检索所有用户?
我是asp.net新手,我有新任务要从Active Directory检索所有用户。当我试图从Active Directory检索所有用户时,我只得到一个用户C# 如何从Active Directory检索所有用户?,c#,asp.net,active-directory,C#,Asp.net,Active Directory,我是asp.net新手,我有新任务要从Active Directory检索所有用户。当我试图从Active Directory检索所有用户时,我只得到一个用户 private void btngetuser_Click(object sender, EventArgs e) { DirectorySearcher searcher = new DirectorySearcher(); searcher.SearchScope = SearchScope.Subtr
private void btngetuser_Click(object sender, EventArgs e)
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", Environment.UserName);
//SearchResult findUser = searcher.FindOne();
foreach (SearchResult findUser in searcher.FindAll())
{
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
string userName = user.Properties["displayName"].Value.ToString();
string Email = user.Properties["mail"].Value.ToString();
string Mobile = user.Properties["Mobile"].Value.ToString();
string Login = user.Properties["sAMAccountName"].Value.ToString();
string[] rt = new string[] { Login, userName, Email, Mobile };
dataGridView1.Rows.Add(rt);
}
}
}
你用的是过滤器,对吗?为什么您希望此按登录名筛选的查询将返回AD中的所有用户,而不是您要求的用户?您可以使用
原则搜索器和“示例查询”原则进行搜索:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for UserPrincipal (users)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
UserPrincipal foundUser = found as UserPrincipal;
if(foundUser != null)
{
string userName = foundUser.DisplayName;
string email = foundUser.Email;
string login = foundUser.SamAccountName;
}
}
}
如果您还没有-请阅读MSDN文章,这篇文章很好地展示了如何最好地利用System.DirectoryServices.AccountManagement
中的新功能。或者查看名称空间。您可能只有一个用户,因为SamAccountName
在用户中必须是唯一的-因此,如果您搜索一个特定的SamAccountName
,您将永远不会得到超过一个的点击率…是的,您已经指定要获取一个特定用户的信息,即当前登录的用户。如果你想获得广告中的所有用户,你必须使用另一个过滤器。在这个中间的某个地方有这个任务的描述。有没有办法用姓氏或名字或其他标准来排序结果?