Active Directory Search from a String using Visual Studio

I have a Code that Returns the Email Address of a User from Active Directory using a Textbox. The Issue is, the User sometimes contains a space before the end of the parenthesis. e.g. Doe, John (Test ) or Doe, John (Test) which makes its difficult to return the value of the email address when the space is present or not. Is there a way to disregard the space when searching via Active Directory?

Private Sub txt_LMName_TextChanged(sender As Object, e As EventArgs) Handles 
txt_LMName.TextChanged

    If txt_LMName.TextLength > 0 Then
        Dim rootEntry As New DirectoryEntry("LDAP://dc=*,dc=*,dc=*")

        Dim UserLMsearcher As New DirectorySearcher(rootEntry)
        UserLMsearcher.PropertiesToLoad.Add("mail")
        UserLMsearcher.Filter = "(&(objectCategory=User)(displayName=" & txt_LMName.Text & "))"

        Dim LMResults As SearchResultCollection
        LMResults = UserLMsearcher.FindAll()

        Dim LMResult As SearchResult

        For Each LMResult In LMResults

            txtTo.Text = LMResult.Properties("mail")(0)

        Next
    Else
    End If
End Sub

1 answer

  • answered 2019-02-05 07:18 preciousbetine

    Write the filter like this

    UserLMsearcher.Filter = "(&(objectCategory=User)(|(displayName=" & txt_LMName.Text & ")(displayName=" & txt_LMName.Text & " )))"