C# search for user in AD

回眸只為那壹抹淺笑 提交于 2019-12-25 16:26:51

问题


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!


回答1:


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());



回答2:


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



来源:https://stackoverflow.com/questions/25757712/c-sharp-search-for-user-in-ad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!