[c#] How can I get a list of users from active directory?

How can I get a list of users from active directory? Is there a way to pull username, firstname, lastname? I saw a similar post where this was used:

 PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

I have never done anything with active directory so I am completely lost. Any help would be greatly appreciated!

This question is related to c# asp.net .net active-directory

The answer is


Include the System.DirectoryServices.dll, then use the code below:

DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";

foreach (DirectoryEntry child in directoryEntry.Children)
{
    if (child.SchemaClassName == "User")
    {
        userNames += child.Name + Environment.NewLine   ;         
    }

}
MessageBox.Show(userNames);

Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.

Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.

using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
    List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
    foreach(var u in users)
        {
            DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
            Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
        }
}

PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.

Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx

Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all

using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
    using (var searcher = new DirectorySearcher(root))
    {
        // looking for a specific user
        searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
        // I only care about what groups the user is a memberOf
        searcher.PropertiesToLoad.Add("memberOf");

        // FYI, non-null results means the user was found
        var results = searcher.FindOne();

        var properties = results?.Properties;
        if (properties?.Contains("memberOf") == true)
        {
            // ... iterate over all the groups the user is a member of
        }
    }
}

Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.

For authenticating the user:

using (var context = new PrincipalContext(ContextType.Domain))
{
    return context.ValidateCredentials(username, password);
}

If you want to filter y active accounts add this to Harvey's code:

 UserPrincipal userPrin = new UserPrincipal(context);
 userPrin.Enabled = true;

after the first using. Then add

  searcher.QueryFilter = userPrin;

before the find all. And that should get you the active ones.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to active-directory

Powershell: A positional parameter cannot be found that accepts argument "xxx" How to switch to another domain and get-aduser How can I verify if an AD account is locked? Powershell script to see currently logged in users (domain and machine) + status (active, idle, away) Querying Windows Active Directory server using ldapsearch from command line How to list AD group membership for AD users using input list? Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory What are CN, OU, DC in an LDAP search? PowerShell script to return members of multiple security groups How do I get specific properties with Get-AdUser