LDAP通过vb.net查询

时间:2014-08-12 16:00:10

标签: vb.net ldap

我试图通过VB.NET编写一个LDAP查询来回退homeDirectory的atrribute并在文本框中输入。以下代码用于查询LDAP用户以检查他们所属的组。如何将下面的内容拉回homeDirectory = textbox1.text。

Private Sub Button3_Click(sender As Object, e As System.EventArgs) Handles Button3.Click
    Dim rootEntry As New DirectoryEntry("fake")
    Dim srch As New DirectorySearcher(rootEntry)

    srch.SearchScope = SearchScope.Subtree
    srch.Filter = "(&(objectClass=user)(sAMAccountName=fake)(memberOf=CN=FAKE,OU=Citrix,OU=SecurityGroups,DC=fake,DC=fake))"
    Dim res As SearchResultCollection = srch.FindAll()

    If res Is Nothing OrElse res.Count <= 0 Then
        MsgBox("This user is *NOT* member of that group")
    Else
        MsgBox("This user is INDEED a member of that group")
    End If
End Sub

现在的样子:

Dim rootEntry As New DirectoryEntry("LDAP://johnsmith.com")
Dim srch As New DirectorySearcher(rootEntry)

srch.SearchScope = SearchScope.Subtree
srch.Filter = "(&(objectClass=user)(sAMAccountName=jsmith)"
srch.PropertiesToLoad.Add("homeDirectory")

Dim res As SearchResultCollection = srch.FindAll()
Dim homeDirectory As String = res(0).Properties("homeDirectory").ToString()
Dim user As SearchResult = res(0)

If user.Properties.Contains("homeDirectory") Then
    TextBox1.Text = user.Properties("homeDirectory").ToString()
End If

If res Is Nothing OrElse res.Count <= 0 Then
    MsgBox("This user is *NOT* member of that group")
Else
    MsgBox("This user is INDEED a member of that group")
End If

1 个答案:

答案 0 :(得分:0)

告诉DirectorySearcher您要加载哪些属性(例如):

srch.PropertiesToLoad.Add("homeDirectory")

您现在可以简化查询,只包含您要查找的用户名:

srch.Filter = "(&(objectClass=user)(sAMAccountName=fake))"

然后,假设您只有一个搜索结果,您应该能够从SearchResultCollection的第一个结果中检索该属性:

Dim user As SearchResult = res(0)
If user.Properties.Contains("homeDirectory") Then
    textbox1.Text = user.Properties("homeDirectory").ToString()
End If