获取用户在Active Directory目录目录、用户、Active、Directory

2023-09-08 13:23:25 作者:朵儿

我写这需要得到用户的列表从指定域的应用程序。我能得到现在的用户,但它的方式来减缓我怎么能做到这一点更快特别是在较大的领域?

I am writing an application that needs to get a list of users from a specified domain. I can get the users now, but it is way to slow how can I do this faster especially on larger domains?

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
        {
            UserPrincipal userPrincipal = new UserPrincipal(pc);

            PrincipalSearcher search = new PrincipalSearcher(userPrincipal);

            PrincipalSearchResult<Principal> results = search.FindAll();

            foreach (var principals in results.Partition(20))
            {
                IDictionary<string, string> users = new Dictionary<string, string>(20);
                foreach (UserPrincipal principal in principals.Cast<UserPrincipal>())
                {
                    users.Add(principal.SamAccountName, principal.DisplayName);
                }

                yield return users;
            }
        }

基本上在外层foreach循环我得到的IEnumerable的一个IEnumerable>。我这样做,这样我就可以尝试逐步加载一些的时间和他们显示给用户,而其余仍在加载,但一旦我打的内环,我收到了几分钟的挂起。

Basically in the outer foreach loop I am getting an IEnumerable of IEnumerable>. I did that so I could try to incrementally load a few at a time and display them to the user while the rest are still loading, but once I hit that inner loop I get a several minute hang.

我试图让域\用户名格式的用户名以及我还没有想出如何做到既。

I am trying to get the users name in domain\username format as well which I haven't figured out how to do either.

推荐答案

试试这个。它应该工作得更快。

Try this. It should work faster.

using System.DirectoryServices;

string[] RetProps = new string[] { "SamAccountName", "DisplayName" };
                //IDictionary<string, string> users = new Dictionary<string, string>();
List<string[]> users = new List<string[]>();

           foreach (SearchResult User in GetAllUsers("YourDomain", RetProps))
           {
            DirectoryEntry DE = User.GetDirectoryEntry();
            try
               {
                users.Add(new string[]{DE.Properties["SamAccountName"][0].ToString(), DE.Properties["DisplayName"][0].ToString()});
               }
               catch
               {
               }
            }


    internal static SearchResultCollection GetAllUsers(string DomainName, string[] Properties)
    {
      DirectoryEntry DE = new DirectoryEntry("LDAP://" + DomainName);
      string Filter = "(&(objectCategory=organizationalPerson)(objectClass=User))";
      DirectorySearcher DS = new DirectorySearcher(DE);
      DS.PageSize = 10000;
      DS.SizeLimit = 10000;
      DS.SearchScope = SearchScope.Subtree;
      DS.PropertiesToLoad.AddRange(Properties); DS.Filter = Filter;
      SearchResultCollection RetObjects = DS.FindAll();
      return RetObjects;
    }
  }
}
 
精彩推荐
图片推荐