在AD中迭代用户组并将其保存在列表中

时间:2016-08-24 18:26:26

标签: c# active-directory ldap

我有一个从AD中检索用户节点的过程:

public static void ConnectActiveDirectory()
{
    List<string> lstGroups = new List<string>();
    DirectoryEntry entry;
    string user = "username";
    string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];

    entry = new DirectoryEntry(@"LDAP://" + server);
    DirectorySearcher searcher = new DirectorySearcher(entry);
    searcher.Filter = "sAMAccountName=" + user;
    searcher.PropertiesToLoad.Add("MemberOf");
    SearchResult result = searcher.FindOne();
}

我们的想法是将所有组保存在字符串列表中,而不执行以下操作:

foreach (ResultPropertyValueCollection s in result.Properties.Values)
{
    string groupname = null;

    for (int i = 0; i < s.Count; i++)
    {
        dn = s[i].ToString();
        equalsIndex = dn.IndexOf("=", 1);
        commaIndex = dn.IndexOf(",", 1);

        groupname = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);

      lstGroups.Add(groupname);
    }
}

我可以在&#39; DirectorySearcher&#39;中使用任何方法吗?类?

另外,有没有办法删除第一个Hashtable?来自SearchResult对象的adspath。

1 个答案:

答案 0 :(得分:0)

您可以使用DirectoryEntry对象向AD询问显示名称,而不是自己解析可分辨名称。例如:

var directoryEntry = new DirectoryEntry(@"LDAP://address");
var directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "samaccountname=user";
directorySearcher.PropertiesToLoad.Add("memberOf");
var result = directorySearcher.FindOne();
foreach (var i in result.Properties["memberOf"])
{
    var group = new DirectoryEntry(@"LDAP://" + i);
    Console.WriteLine(group.Properties["DisplayName"]);
}