c# – Active Directory组枚举

我使用以下代码查询公司LDAP列表.问题是它写出了完整的字符串.除了字符串解析之外,还有一种简单的方法可以写出组名吗?

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;

public class Test
{
    public static void Main()
    {
        string userName = "USER";

        DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://dc=ABC,dc=com");

        DirectorySearcher search = new DirectorySearcher();

        search.Filter = String.Format("(cn={0})", userName);
        search.PropertiesToLoad.Add("memberOf");

        List<string> groupsList = new List<string>();

        SearchResult result = search.FindOne();
        if (result != null)
        {
            int groupCount = result.Properties["memberOf"].Count;

            for (int counter = 0; counter < groupCount; counter++)
            {
                groupsList.Add((string)result.Properties["memberOf"][counter]);
            }
        }

        List<string> list = new List<string>();
        list = groupsList.ToList();

        for (int i = 0; i < list.Count; i++)
        {
            Console.WriteLine(list[i]);
        }

    }

}

最佳答案 我认为解决方案比这更容易.

您正在尝试查找用户的群组,对吗?

private void button1_Click(object sender, EventArgs e)
{
   List<string> userGroups = new List<string>();
   PrincipalContext LdapContext = new PrincipalContext(ContextType.Domain, domainName);
   UserPrincipal user = UserPrincipal.FindByIdentity(LdapContext, userName);

   foreach (var group in user.GetGroups())
   {
       userGroups.Add(group.Name);
   }
}
点赞