从VB.Net中的ActiveDirectory检索SAMAccountName

时间:2019-06-06 13:44:53

标签: active-directory visual-studio-2017 username user-profile

在我的应用程序中,我有一个“受众群体选择器”,可让您在Active Directory中搜索组和用户。小组成员可以用一种方式,但是用户群存在问题。

这是我的代码:

Public Function GetGroups() As List(Of String)
    Dim objADAM As DirectoryEntry                   ' Binding object.
    Dim objGroupEntry As DirectoryEntry             ' Group Results.
    Dim objSearchADAM As DirectorySearcher          ' Search object.
    Dim objSearchResults As SearchResultCollection  ' Results collection.
    Dim strPath As String                           ' Binding path.
    Dim result As New List(Of String)

    strPath = "LDAP://MYDOMAINCONTROLLER.MYDOMAIN"
        objADAM = New DirectoryEntry(strPath)
        objADAM.RefreshCache()

    Try
        objSearchADAM = New DirectorySearcher(objADAM)
        objSearchADAM.Filter = "(&(objectClass=" & AudienceSelector.searchtype.Text & ")(cn=" & AudienceSelector.TextBox1.Text & "))"
        objSearchADAM.SearchScope = SearchScope.Subtree
        If AudienceSelector.searchtype.Text = "user" Then
            objSearchADAM.PropertiesToLoad.Add("SAMAccountName")
        End If
        objSearchResults = objSearchADAM.FindAll()
    Catch e As Exception
    End Try

    Try
        If objSearchResults.Count <> 0 Then
            Dim objResult As SearchResult
            For Each objResult In objSearchResults
                objGroupEntry = objResult.GetDirectoryEntry
                result.Add(objGroupEntry.Name)
            Next objResult
        End If
    Catch e As Exception
    End Try
    Return result
End Function

因此,如果AudienceSelector.searchtype = user,则返回用户列表,但是我得到了友好名称,并且需要SAMAccountName。 因此,我取而代之的是“约翰·史密斯”而不是“ john.smith”。

我进行了搜索,并尝试添加PropertiesToLoad位以引入SAMAcountName,但这每次都给我一个友好的名称。

谁能看到我要去哪里错了?

在此先感谢您的帮助:-D

1 个答案:

答案 0 :(得分:0)

我不得不抢夺属性,而不是objGroupEntry.Name。

稍后有一个简单的if语句,并且此...

 Dim thisuserSAN As String = objGroupEntry.Properties("SamAccountName").Value.ToString.ToLower
                    result.Add(thisuserSAN)

...起到了作用:)