65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 VB.NET 访问 LDAP 用户列表

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (9投票s)

2004年10月6日

2分钟阅读

viewsIcon

412277

本文将解释如何使用 VB.NET 访问 LDAP 服务。

引言

读取所有 LDAP 用户列表

与 VB 6.0 相比,.NET 框架为 LDAP 等网络解决方案提供了非常简便的访问方式。我看到很多人询问如何使用 .NET 访问 LDAP。 在本文中,我将尝试解释如何检索所有 LDAP 用户的列表。

代码

 Public Function GetAllUsers(ByVal ldapServerName As String) As Hashtable 

 'To retrieve list of all  LDAP users 

 'This function returns HashTable
 _ldapServerName = ldapServerName

 Dim sServerName As String = "mail"

 Dim oRoot As DirectoryEntry = New DirectoryEntry("LDAP://" & ldapServerName & _
       "/ou=People,dc=mydomainname,dc=com")
 
 Dim oSearcher As DirectorySearcher = New DirectorySearcher(oRoot)
 Dim oResults As SearchResultCollection
 Dim oResult As SearchResult
 Dim RetArray As New Hashtable()

 Try

  oSearcher.PropertiesToLoad.Add("uid")
  oSearcher.PropertiesToLoad.Add("givenname")
  oSearcher.PropertiesToLoad.Add("cn")
  oResults = oSearcher.FindAll     

  For Each oResult In oResults

   If Not oResult.GetDirectoryEntry().Properties("cn").Value = "" Then
    RetArray.Add( oResult.GetDirectoryEntry().Properties("uid").Value, _
      oResult.GetDirectoryEntry().Properties("cn").Value)
   End If

  Next

 Catch e As Exception

  'MsgBox("Error is " & e.Message)
  Return RetArray

 End Try

 Return RetArray
  
 End Function

详细说明

作为基础,当我们编写与 LDAP 相关的应用程序时,我们需要引用 System.DirectoryServices 命名空间。要添加引用,只需右键单击项目并选择“添加引用”。这将呈现一个界面,用于选择可以在项目中引用的 .NET 组件。 在此列表中,选择 System.DirectoryServices.dll 并单击“添加”。 现在,在项目中,打开窗体并在顶部添加以下行

Imports System.DirectoryServices

完成此操作后,System.DirectoryServices 在应用程序中可访问。

LDAP 实现

通常,LDAP 的所有元素和对象都存储在树状结构中。要访问此树状结构,我们需要一个根元素,可以使用它来迭代所有子元素。

获取 LDAP 的根元素

Dim oRoot As DirectoryEntry = New DirectoryEntry("LDAP://" & _
     ldapServerName & "/ou=People,dc=mydomainname,dc=com")

使用此行,我们可以获得 LDAP 树状结构的根。

现在,下一步是在 LDAP 树中找到所有用户条目。对于此搜索操作,.NET Framework 提供了一个类,即 DirectorySearcher

Dim oSearcher As DirectorySearcher = New DirectorySearcher(oRoot)

该类需要一个 DirectoryEntry 参数,并以 SearchResultCollection 的形式返回数据。

要访问 SearchResultCollection,我们需要使用 SearchResult 对象。搜索结果将包含我们在加载属性中指定的字段。要指定要加载的属性,我们需要将字段名作为字符串传递给搜索器对象的 PropertiesToLoad 方法。

例如

oSearcher.PropertiesToLoad.Add("givenname")

请确保指定正确的字段名称。

现在,搜索器对象的 FindAll 方法将返回 SearchResults 集合。此集合将包含 SearchResult(如上所述),并将包含具有加载属性的目录条目。

在此示例中,我将所有值放在一个 HashTable 中,其中 Unique ID (UID) 作为键,Common Name (cn) 作为值。

© . All rights reserved.