使用System.DirectoryServices.AccountManagement搜索组织内所有用户的一般方法?

时间:2016-05-16 20:35:04

标签: c# active-directory ldap

我正在尝试弄清楚如何使用 System.DirectoryServices.AccountManagement 在组织中使用电子邮件地址返回所有用户,但是我想这样做而不必指定域。

这将用于将安装在组织内的服务器PC上的Windows服务中,理想情况下,我不希望每个客户端在安装时都必须在其域中输入。

目前我使用以下内容:

context = New PrincipalContext(ContextType.Domain)

Using userPrin As New UserPrincipal(context)
    userPrin.Enabled = True
    userPrin.EmailAddress = "*"
    Using searcher = New PrincipalSearcher(New UserPrincipal(context))
        searcher.QueryFilter = userPrin

        Using results As PrincipalSearchResult(Of Principal) = searcher.FindAll
            Trace.WriteLine("results.count: " & results.Count)
            userPrincipalResult = (From r In results Select TryCast(r, UserPrincipal))
            Trace.WriteLine("userPrincipalResult.Count: " & userPrincipalResult.Count)
            userList = (From cr In userPrincipalResult Select cr.EmailAddress).ToList()
        End Using

    End Using
End Using

这样做的问题是,如果主域名为@client.com,但他们在同一个林中有另一个域@clientdifferent.com,则它不会返回此其他域中的任何用户。

我发现帖子说明您可以搜索GC而不是LDAP来搜索更高级别,但这需要添加域名和端口号。有没有办法在不指定任何域的情况下做类似的事情?

链接:

How to search in multiple domains using System.DirectoryServices.AccountManagement?

When do I need a Domain Name and a Domain Container to create a PrincipalContext?

C# - Searching for users across multiple Active Directory domains

1 个答案:

答案 0 :(得分:0)

这样的事情会起作用吗?

Using tempForest = ActiveDirectory.Forest.GetCurrentForest()
    For Each domain As ActiveDirectory.Domain In tempForest.Domains
        context = New PrincipalContext(ContextType.Domain, domain.Name)
        Using userPrin As New UserPrincipal(context)
            userPrin.Enabled = True
            userPrin.EmailAddress = "*"
            Using searcher = New PrincipalSearcher(New UserPrincipal(context))
                searcher.QueryFilter = userPrin

                Using results As PrincipalSearchResult(Of Principal) = searcher.FindAll
                    Trace.WriteLine("results.count: " & results.Count)
                    userPrincipalResult = (From r In results Select TryCast(r, UserPrincipal))
                    Trace.WriteLine("userPrincipalResult.Count: " & userPrincipalResult.Count)
                    userList = (From cr In userPrincipalResult Select cr.EmailAddress).ToList()
                End Using

            End Using
        End Using
    Next
End Using