如何通过C#以编程方式获取Active Directory林的根目录

时间:2016-11-10 06:39:53

标签: c# active-directory directoryservices

我的客户有一个巨大的Active Directory。例如:

company.com
  de.company.com
  us.company.com
  in.company.com
  xx.company.com

当我得到当前用户时,我得到domainname\username。当我抓住域名并希望在这个域中搜索世界上的其他用户时,我无法知道我需要知道company.com进行目录搜索。

在C#中是否有办法获取我使用DirectorySearcher或任何其他C#方法查询AD的根对象?

2 个答案:

答案 0 :(得分:2)

root forest name可以从RootDSE分区获取。查看rootDomainNamingContext属性。这个wiil返回你的林根域。我不建议从用户DN中提取林名称,因为如果您在一个林中有2个域树,它将不起作用。第二种选择是在当前域的全局编录中搜索用户。全局编录包含整个林中所有用户的部分副本

以下代码执行全局编录搜索。我有2个域,在我的林中,所以它返回给我2个用户。请注意,您必须处理多个返回的结果:

        var forest = Forest.GetCurrentForest();
        var globalCatalog = GlobalCatalog.FindOne(new DirectoryContext(DirectoryContextType.Forest, forest.Name));

        using (var connection = new LdapConnection(new LdapDirectoryIdentifier(globalCatalog.Name, 3268)))
        {
            var entries = new List<SearchResultEntry>();

            var searchRequest = new SearchRequest(string.Empty, "(samaccountname=administrator)", SearchScope.Subtree, null);
            var searchOptionsControl = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);

            searchRequest.Controls.Add(searchOptionsControl);

            var pageResultRequestControl = new PageResultRequestControl(1000);

            searchRequest.Controls.Add(pageResultRequestControl);

            do
            {
                var response = (SearchResponse)connection.SendRequest(searchRequest);

                if (response != null)
                {
                    if (response.ResultCode != ResultCode.Success)
                    {
                        throw new ActiveDirectoryOperationException(response.ErrorMessage, (int) response.ResultCode);
                    }

                    foreach (var c in response.Controls.OfType<PageResultResponseControl>())
                    {
                        pageResultRequestControl.Cookie = c.Cookie;
                        break;
                    }

                    entries.AddRange(response.Entries.Cast<SearchResultEntry>());
                }
            }
            while (pageResultRequestControl.Cookie != null && pageResultRequestControl.Cookie.Length > 0);
        }

关于此代码的几点说明: 1.当然这个代码不是生产代码。您可以编写更一般的LdapSearcher,例如可以找到一个here。如果需要,您可以创建此搜索器的同步版本。 2.我强烈建议在基于服务的应用程序中使用LdapConnection而不是DirectorySearcher,因为在企业环境中使用DirectorySearcher会导致内存泄漏和其他issues

答案 1 :(得分:0)

要获取用户的根对象,请使用属性或属性distinguished name来确定Active Direcotry中的完全限定路径。从右边读取结构并提取根元素。

电子。 G。 cn=John Doe, ou=People, dc=sun.com

enter image description here