在AD C中按属性搜索#

时间:2014-08-11 17:08:43

标签: c# active-directory

我目前能够使用以下方式通过NT ID搜索AD:

PrinciplayContext domain = new PrincipalContext(ContextType.Domain)
UserPrincipal byName = UserPrincipal.FindByIdentity(domain, txtTest.Text.Trim());

从那里我可以轻松找到任何和所有扩展。

我想要做的是能够使用employeeID属性获取并获取sn,SAMAccountName,EmployeeID

我想知道是否有办法创建一个新的UserPrincipal并以这种方式进行搜索。 例: UserPrincipal.FindByEmplyeeID

我在想这样的事情:

   public static new UserPrincipal FindByEmployeeID(PrincipalContext context, string identityValue)
   {

      //dont know what to do here... sorry noob on this
   }

例如:

当我使用时:

    try
    {
        PrincipalContext AD = new PrincipalContext(ContextType.Domain);
        UserPrincipal byEmployeeID = UserPrincipal.FindByIdentity(AD, "(&(objectCategory=person)(objectclass=user)(employeID=JR02251206))");
        MessageBox.Show(byEmployeeID.GetEmail());


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

我得到例外:

对象引用未设置为对象的实例。我试过只使用justcial(employeeID = JR02251206)或(objectclass = user)(employeeID = JR02251206),我得到了同样的错误。

2 个答案:

答案 0 :(得分:0)

解决方案:

    try
    {
        DirectoryEntry enTry = new DirectoryEntry("LDAP://OU=Users,OU=Users and Groups,OU=Gentiva,DC=Gentiva,DC=GHSNet,DC=com");
        DirectorySearcher mySearcher = new DirectorySearcher(enTry);
        mySearcher.Filter = "(&(objectClass=user)(extensionAttribute13=" + txtTest.Text.Trim() + "))";
        SearchResult result = mySearcher.FindOne();
        txtBlob.Text = result.Properties["displayname"][0].ToString() +"\n";
        txtBlob.Text += result.Properties["mail"][0].ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

答案 1 :(得分:0)

试试这个:

PrinciplayContext AD= new PrincipalContext(ContextType.Domain)
UserPrincipal searchTemplate = new UserPrincipal(AD);
searchTemplate.EmployeeId = tempUserId;
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal) ps.FindOne();

那应该接近你开始的......

Kevin Orcutt