我一直在敲打我的脑袋已经有一段时间了,无法让它发挥作用。我有一个LDAP查询我确实在AD用户和计算机上工作,但不知道如何在C#中以编程方式进行。
以下是我的LDAP查询在AD工具中正常工作:(memberOf = CN = AccRght,OU = Groups,OU = P,OU = Server,DC = mydomain,DC = com)(objectCategory = user)(objectClass) =用户)(L =城)
我已使用此代码获取用户帐户以获取CN = AccRght的成员,但我没有成功限制属于特定城市的用户。
public StringCollection GetGroupMembers(string strDomain, string strGroup)
{
StringCollection groupMemebers = new StringCollection();
try
{
DirectoryEntry ent = new DirectoryEntry("LDAP://DC=" + strDomain + ",DC=com");
DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");
SearchResultCollection coll = srch.FindAll();
foreach (SearchResult rs in coll)
{
ResultPropertyCollection resultPropColl = rs.Properties;
foreach( Object memberColl in resultPropColl["member"])
{
DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
object obVal = userProps["sAMAccountName"].Value;
if (null != obVal)
{
groupMemebers.Add(obVal.ToString());
}
}
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return groupMemebers;
}
感谢您的帮助!
答案 0 :(得分:1)
如果您实际上正在寻找递归枚举组成员的方法,可能需要使用memberof的递归版本(您可以使用(memberof:1.2.840.113556.1.4.1941:=(cn=Group1,OU=groupsOU,DC=x)))
语法实现)。
此处有更多信息:http://msdn.microsoft.com/en-us/library/aa746475(VS.85).aspx
答案 1 :(得分:1)
嗯,基本上你只需要将你在工具中使用的LDAP过滤器传输到DirectorySearcher中 - 就像这样:
public StringCollection GetGroupMembers(string strDomain, string strGroup)
{
StringCollection groupMemebers = new StringCollection();
try
{
DirectoryEntry ent = new DirectoryEntry("LDAP://DC=" + strDomain + ",DC=com");
DirectorySearcher srch = new DirectorySearcher();
// build the LDAP filter from your (CN=strGroup) part that you had
// in the constructor, plus that filter you used in the AD tool
// to "AND" those together, use the LDAP filter syntax:
// (&(condition1)(condition2))
srch.Filter = string.Format("(&(CN={0})(memberOf=CN=AccRght,OU=Groups,OU=P,OU=Server,DC=mydomain,DC=com)(objectCategory=user)(objectClass=user)(l=City))", strGroup);
SearchResultCollection coll = srch.FindAll();
foreach (SearchResult rs in coll)
{
ResultPropertyCollection resultPropColl = rs.Properties;
foreach( Object memberColl in resultPropColl["member"])
{
DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
object obVal = userProps["sAMAccountName"].Value;
if (null != obVal)
{
groupMemebers.Add(obVal.ToString());
}
}
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return groupMemebers;
}
这应该将该过滤器应用于您的搜索,例如您现在应该只返回该特定城市的用户。
绝对查看此MSDN文章Managing Directory Security Principals in the .NET Framework 3.5 - S.DS.AM的优秀介绍! : - )