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!
Include the System.DirectoryServices.dll, then use the code below:
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a
distinguished name
. The distinguished name is like thisCN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com
. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from
System.DirectoryServices
or SearchRequest fromSystem.DirectoryServices.Protocol
.For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from
System.DirectoryServices.AccountManagement
. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.Note that on the AD user object, there are a number of attributes. In particular,
givenName
will give you theFirst Name
andsn
will give you theLast Name
. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One issamAccountName
, which is also known as pre-Windows 2000 user logon name.userPrincipalName
is generally used after Windows 2000.If you want to filter y active accounts add this to Harvey's code:
after the first using. Then add
before the find all. And that should get you the active ones.
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.