C#Active Directory调用非常慢

时间:2014-08-07 18:29:32

标签: c# performance active-directory directoryservices

我的应用程序需要包含特定安全组中用户的名称和电子邮件地址列表。我目前正在使用下面的代码执行此操作。当我在VPN上运行时,它会在一两秒内立即回来,但是当我在以太网或无线上运行时(两者都在域上),这需要大约40秒才能恢复。有什么方法可以在以太网或无线上改善这种方法的时间吗?

        ...
        DirectoryEntry entry = new DirectoryEntry(ldap);
        DirectorySearcher mySearcher = new DirectorySearcher(entry);
        mySearcher.Filter = "(&(objectCategory=group)(objectClass=group)(groupType:1.2.840.113556.1.4.803:=2147483648))";
        mySearcher.PropertiesToLoad.Add("member");

        SearchResultCollection results = mySearcher.FindAll();
        foreach (SearchResult result in results)
        {
            foreach (string distinguishedMember in result.Properties["member"])
            {
                string memberPath = "LDAP://" + distinguishedMember;
                DirectoryEntry member = new DirectoryEntry(memberPath);
                DirectorySearcher Searcher = new DirectorySearcher(member);
                Searcher.Filter = "(&(objectCategory=user))";
                Searcher.PropertiesToLoad.Add("mail");
                Searcher.PropertiesToLoad.Add("name");
                SearchResult memberFound = Searcher.FindOne();

                if (memberFound != null)
                {
                    String memberEmail = memberFound.Properties["mail"][0].ToString();
                    String memberName = memberFound.Properties["name"][0].ToString();
                    users.Add(new KeyValuePair<String, String>(memberName, memberEmail));
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

也许有助于让所有用户一次性使用,而不是一个一个地取出它们*:

Searcher.Filter = "(&(objectCategory=user)(memberOf=" + myGroupsDistinguishedName + "))"
Searcher.PropertiesToLoad.Add("mail");
Searcher.PropertiesToLoad.Add("name");
var allMembers = Searcher.FindAll();
var users = allMembers.Cast<SearchResult>().ToDictionary(sr=>sr.Properties["name"].ToString(), sr=>sr.Properties["mail"].ToString());

*这不会处理超过1000个用户的情况。

答案 1 :(得分:0)

不要一次获取所有成员,而是使用DirectorySearcher类的pagesize功能。

mySearcher.PageSize = 10;