【问题标题】:How to retrieve all users from Active Directory?如何从 Active Directory 中检索所有用户?
【发布时间】:2013-11-24 09:43:51
【问题描述】:

我是 asp.net 的新手,我有新任务要从 Active Directory 中检索所有用户。当我尝试从 Active Directory 中检索所有用户时,我只有一个用户。

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);
            }
        }
    }

【问题讨论】:

  • 您可能只有一个用户,因为 SamAccountName 在用户中必须是唯一的 - 因此,如果您搜索一个特定的 SamAccountName,您将永远不会得到超过一个 ....

标签: c# asp.net active-directory


【解决方案1】:

您可以使用PrincipalSearcher 和“示例查询”主体进行搜索:

// 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 文章 Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或查看MSDN documentation on the System.DirectoryServices.AccountManagement 命名空间。

【讨论】:

  • 有没有办法按姓氏或名字或其他标准对结果进行排序?
【解决方案2】:

您正在使用过滤器,对吗?为什么您期望这个按登录名过滤的查询会返回 AD 中的所有用户,而不是您所要求的?

【讨论】:

  • 嗯,是的,您已经指定要获取有关某个特定用户的信息 - 即当前登录的用户。如果要获取 AD 中的所有用户,则必须使用另一个过滤器。在这个article 中间的某个地方有这个任务的描述。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
相关资源
最近更新 更多