如何从Active Directory中检索所有用户? [英] How to retrieve all users from Active Directory?

查看:67
本文介绍了如何从Active Directory中检索所有用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to asp.net, I have new tasks to retrieve all users from Active Directory. When I tried to retrieve all users from Active Directory I only got one user.

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

推荐答案

您可以使用 PrincipalSearcher 和按示例查询"委托人进行搜索:

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// 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文章管理目录安全性.NET Framework 3.5 中的主体很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能.或参阅System.DirectoryServices.AccountManagement上的 MSDN文档名称空间.

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

这篇关于如何从Active Directory中检索所有用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆