简体   繁体   中英

How to retrieve all users from 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);
            }
        }
    }

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

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.

You're using a filter, right? Why are you expecting that this query filtered by login name would return all users in AD and not exactly what you asked it for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM