4

我正在使用以下代码查询公司 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]);
        }

    }

}
4

1 回答 1

2

我认为解决方案比这更容易。

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

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);
   }
}
于 2012-11-05T12:28:41.083 回答