.NET Active Directory - 获取特定Active Directory组中的用户列表

问题描述:

我有一个使用Ldap查询的组名列表...我已经将列表名称绑定到WinForms应用程序中的数据网格。当用户选择的组名称中的一个,一个事件被触发,组名被传递到下面的方法: -.NET Active Directory - 获取特定Active Directory组中的用户列表

// Get a list of group specific users // 
    private List<Users> GetUsers(string groupName) 
    { 
     List<Users> groupSpecificUsers = new List<Users>(); 
     DirectorySearcher ds = null; 
     DirectoryEntry de = new DirectoryEntry(domainPath); 
     ds = new DirectorySearcher(de); 

     ds.PropertiesToLoad.Add("SAMAccountName"); 
     ds.PropertiesToLoad.Add("member"); 
     ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 
     SearchResult sr = ds.FindOne(); 

     if (sr != null) 
     { 
       // do whatever you need to do with the entry 
     } 

.... return list of users that belong to the specific GroupName .... 

当我把一个断点在if语句... SR被列为null ...我不理解为什么它的空...即使选定的组明确地有其成员...

我觉得,我不太明白如何使用特定的组名称ldap查询...任何人都可以指向正确的方向吗?

+0

我觉得SR,因为你是在SAM帐户名搜索可能是空的但代替您提供组名称的帐户名称。 SAMAccountName应该是用于登录到AD的名称。因此,ds.filter行只会返回1个项目(假设某人的帐户名称与组名相同) –

你必须采取domainPath,我推测性的参数DirectoryEntry对象是在你的代码字段某处(?)。如果你可以尝试从根只是在寻找,你可以试试这个代码,看看你是否得到更好的结果:

// Get a list of group specific users // 
private List<Users> GetUsers(string groupName) 
{ 
    List<Users> groupSpecificUsers = new List<Users>(); 
// MAKE SURE THE NEXT LINE REFLECTS YOUR DOMAIN 
    DirectorySearcher ds = (new DirectoryEntry("LDAP://dc=yourdomain,dc=tld")); 
    ds.PropertiesToLoad.Add("samaccountname"); 
    ds.PropertiesToLoad.Add("member"); 
    ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 
    SearchResult sr = ds.FindOne(); 

    if (sr != null) 
    { 
      // do whatever you need to do with the entry 
    } 

看看这些变化解决您的问题。

+0

谢谢山姆,我得到的错误...不能隐式地从目录条目转换到目录搜索器。在LDAP:// dc = yourdomain语句上。 – Philo

+0

我将其更改为目录搜索器并修复了语法错误。但由于sr的结果仍然为空... – Philo

+0

语法错误的道歉。我也对它进行了测试,但得到的结果。您是否肯定DirectoryEntry的LDAP://参数是正确的,并且该组实际上对成员有用吗? – Sam

我认为下面一行:

ds.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 

需要被改为:

ds.Filter = "(&(objectClass=group)(Group=" + groupName + "))"; 
+0

仍然没有结果.... null返回sr – Philo

+0

您可能需要添加“ds.PropertiesToLoad 。新增( “组”);”在运行过滤器之前。 –

+0

仍然没有去。 //ds.PropertiesToLoad.Add("SAMAccountName“); //ds.PropertiesToLoad.Add("member“); ds.PropertiesToLoad.Add(“Group”); ds.Filter =“(&(objectClass = group)(Group =”+ groupName +“))”; – Philo

这是我如何解决它(这是几乎什么萨姆说,我调整它多一点用于说明目的): -

  List<Users> groupSpecificUsers = new List<Users>(); 
      DirectoryEntry ROOT = new DirectoryEntry("LDAP://DC=xxx,DC=net"); 
      DirectoryEntry de = ROOT; 

      var sr = new DirectorySearcher(de); 
      sr.PropertiesToLoad.Add("SAMAccountName"); 
      sr.PropertiesToLoad.Add("member"); 
      sr.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))"; 



      if (sr != null) 
      {...whatever...}