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

.NET Active Directory - Get a list of users in a specific Active Directory Group

我有一个使用 Ldap 查询的组名称列表...我已将列表名称绑定到 WinForms 应用程序中的数据网格。当用户选择其中一个组名时,将触发一个事件并将组名传递给以下方法:-

    // 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 被列为空...我不明白为什么它为空...即使所选组中显然有成员...

我觉得,我不太明白在 ldap 查询中如何使用特定的组名...谁能指出我正确的方向?

我认为下面一行:

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

需要改为:

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

您的 DirectoryEntry 对象采用了 domainPath 参数,我认为它是您代码中某处的一个字段(?)。如果您可以尝试从根搜索,您可以尝试使用此代码查看是否获得更好的结果:

// 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
    }

查看这些更改是否解决了您的问题。

这就是我解决它的方法(这几乎是 Sam 所说的,为了说明目的我稍微调整了一下):-

            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...}