在AD c#中按属性搜索
本文关键字:属性 搜索 AD | 更新日期: 2023-09-27 18:17:34
我目前能够通过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());
}
我得到一个异常:
对象引用未设置为对象的实例。我已经尝试使用只是(employeeID=JR02251206)或(objectclass=user)(employeeID=JR02251206)的原则,我得到同样的错误。
试试这个:
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解决方案:
try
{
DirectoryEntry enTry = new DirectoryEntry("LDAP://OU=Users,OU=Users and Groups,DC=BLAH,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());
}