msindle
msindle

Reputation: 239

C# search for user in AD

I'm not a programmer by nature so I apologize in advance. I've searched far and wide and have found bits and pieces of 10 different ways to do one thing. What I'm trying to do seems very simple but I'm missing it...I need to search Active Directory using a first name and last name and display all users who match in a listbox. Can someone point me in the right direction, or if someone has already asked the same question link me to it? Thanks in advance!

Upvotes: 0

Views: 2783

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

Try something like this:-

DirectorySearcher d = new DirectorySearcher(somevalue);    
d.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(givenname={0})(sn={1}))", firstname, lastname);

Also from How to search for users in Active Directory with C#

//Create a shortcut to the appropriate Windows domain
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain,
                                                      "myDomain");

//Create a "user object" in the context
using(UserPrincipal user = new UserPrincipal(domainContext))
{
 //Specify the search parameters
 user.Name = "he*";

 //Create the searcher
 //pass (our) user object
 using(PrincipalSearcher pS = new PrincipalSearcher())
 {
  pS.QueryFilter = user;

  //Perform the search
  using(PrincipalSearchResult<Principal> results = pS.FindAll())
  {
   //If necessary, request more details
   Principal pc = results.ToList()[0];
   DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject();
  }
 }
} 
//Output first result of the test
MessageBox.Show(de.Properties["mail"].Value.ToString());

Upvotes: 2

msindle
msindle

Reputation: 239

Of course shortly after posting I found my answer :)

 // create your domain context
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "servername","username","password");

            UserPrincipal qbeUser = new UserPrincipal(ctx);
            qbeUser.GivenName = "fname";
             qbeUser.Surname = "lname";
          //   qbeUser.DisplayName= "fname lname";    

            PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

            // find all matches
            foreach (var found in srch.FindAll())
            {
                lstUser.Items.Add(found.ToString());
            }

here is the link: Search Users in Active Directory based on First Name, Last Name and Display Name

Upvotes: 0

Related Questions