Johnrad
Johnrad

Reputation: 2655

How to get and filter AD first & last name in ASP.NET

I am trying to search by AD username and display the First and Last Name to a table.

This is what I have so far:

DirectoryEntry myLDAPConnection = new DirectoryEntry("LDAP://company.com");
DirectorySearcher dSearch = new DirectorySearcher(myLDAPConnection);

I understand I need to do something with my dSearch object to filter what is returned, but I have no clue what to do beyond this.

Upvotes: 4

Views: 816

Answers (1)

marc_s
marc_s

Reputation: 754598

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }

    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

    // if found....
    if (group != null)
    {
       // iterate over members
       foreach (Principal p in group.GetMembers())
       {
           Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
           // do whatever you need to do to those members
       }
    }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Upvotes: 3

Related Questions