活动目录:获取用户所在的组

Kri*_*s-I 3 c# active-directory

我想找到用户所在的组列表.我从http://www.codeproject.com/KB/system/everythingInAD.aspx尝试了几个解决方案 但没有结果.

这段代码给我一个"真实",表示LDAP正在运行:

public static bool Exists(string objectPath)
{
    bool found = false;
    if (DirectoryEntry.Exists("LDAP://" + objectPath))
        found = true;
    return found;
}
Run Code Online (Sandbox Code Playgroud)

谢谢,

更新1:

public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", "LDAP-Server",
        groupMemberships, recursive);
}

public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}
Run Code Online (Sandbox Code Playgroud)

我有一个例外:

PropertyValueCollection ValueCollection = ent.Properties[attributeName];
Run Code Online (Sandbox Code Playgroud)

"COMException未处理"

Jak*_*sen 8

在.NET 4中,您可以UserPrincipal通过以下方式使用新类轻松完成此操作:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "your_login");
    foreach (var group in user.GetGroups())
    {
        Console.WriteLine(group.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

您必须添加引用System.DirectoryServices.AccountManagement以引入所需的类型.