在ActiveDirectory(.NET)中搜索联系人

时间:2016-06-22 18:44:17

标签: .net active-directory

我有一个应用程序需要从Active Directory中提取联系人。

以下是我正在使用的代码:

Public Function GetADContacts(ByVal LastNameStarts As String) As DirectoryServices.SearchResultCollection
    Dim rootDSE As New DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    Dim defaultNamingContext As String = rootDSE.Properties("defaultNamingContext").Value.ToString()
    Dim objSearch As New DirectoryServices.DirectorySearcher()
    Dim cllQueryResults As DirectoryServices.SearchResultCollection

    With objSearch
        .SearchRoot = New DirectoryServices.DirectoryEntry("LDAP://" + defaultNamingContext)
        .Filter = "(&(objectclass=contact)(mailNickname=*)(cn=*)(sn=" + LastNameStarts + "*)(givenname=*))"
        .SearchScope = DirectoryServices.SearchScope.Subtree
        .PropertiesToLoad.AddRange(New String() {"cn", "sn", "givenname", "mailNickname"})
        .Sort.PropertyName = "sn"
        .Sort.Direction = DirectoryServices.SortDirection.Ascending
        cllQueryResults = .FindAll()
    End With

    Return cllQueryResults
End Function

我已经检查过以确保联系人设置了sn,cn,givenname和mailNickname属性,但没有返回任何内容。当我将objectcategory更改为user时,我会获得所有用户,但对于联系人,我什么都没得到。

我有什么问题吗?

1 个答案:

答案 0 :(得分:0)

如果您只想搜索联系人,则过滤器应如下所示:

Searcher.Filter = "(&(objectCategory=person)(objectClass=contact))"

这里有一个小例子来获取所有联系人的DN:

Dim Searcher As New DirectorySearcher("LDAP://")
Dim QueryResults As SearchResultCollection
Dim Result As SearchResult

Searcher.PropertiesToLoad.Add("distinguishedName")
Searcher.Filter = "(&(objectCategory=person)(objectClass=contact))"

QueryResults = Searcher.FindAll

For Each Result In QueryResults
    Console.WriteLine(Result.Properties("distinguishedName")(0))
Next

Console.ReadLine()

有关此主题的非常有用的文章:Active Directory: LDAP Filter Syntax。可悲的是,我没有保存链接..我稍后会尝试提供它。