如何从Active Directory检索所有用户?

时间:2013-11-24 09:43:51

标签: 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.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);
            }
        }
    }

2 个答案:

答案 0 :(得分: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 = user.Email;
            string login = user.SamAccountName;
        }
   }
}

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。

答案 1 :(得分:0)

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