简体   繁体   English

C#在AD中搜索用户

[英]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. 我搜索了很多东西,发现了零碎的10种不同方法来做一件事情。 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. 我正在尝试做的事情看起来很简单,但我很想念...我需要使用名字和姓氏搜索Active Directory,并在列表框中显示所有匹配的用户。 Can someone point me in the right direction, or if someone has already asked the same question link me to it? 有人可以指出我正确的方向,还是有人已经问过相同的问题,将我链接到该方向? Thanks in advance! 提前致谢!

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# 另请参见如何使用C#在Active Directory中搜索用户

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

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 这是链接: 根据名字,姓氏和显示名称在Active Directory中搜索用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM