How do we get Total Count of all Active Directory Users list from the Domain in C#..?

BeUnique 2,332 Reputation points
2024-03-25T12:26:36.56+00:00

I am getting individual list and group list from AD, but, i want one simple steps to get the count of Active Directory Users (instead of foreach loop)..

How do we get Total Count of all Active Directory Users list from the Domain in C#.

How to do this...?

Windows for business Windows Client for IT Pros Directory services Active Directory
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-03-26T02:26:35.2333333+00:00

    Hi @BeUnique , Welcome to Microsoft Q&A,

    To get the number of Active Directory users from C# without using a foreach loop, you can use the PrincipalSearcher class in the System.DirectoryServices.AccountManagement namespace. This allows you to perform a simple query to get the number of users. Below is a sample code in C# to get the number of Active Directory users without using a foreach loop, you can use the PrincipalSearcher class in the System.DirectoryServices.AccountManagement namespace. This allows you to perform a simple query to get the number of users. The following is a sample code

    using System;
    using System.DirectoryServices.AccountManagement;
    using System.Linq;
    
    namespace xxx
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                int userCount = GetActiveDirectoryUserCount();
                Console.WriteLine("Active Directory counts: " + userCount);
                Console.ReadLine();
            }
            static int GetActiveDirectoryUserCount()
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                {
                    UserPrincipal userPrincipal = new UserPrincipal(context);
                    PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);
                    var results = searcher.FindAll();
                    return results.Count();
                }
            }
        }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.