VB.NET:从AD获取全名

时间:2011-10-27 20:01:01

标签: .net vb.net visual-studio visual-studio-2010 ldap

我正在尝试获取用户名为“domain \ usarname”的用户的全名。尝试了几个不同的例子,但似乎都没有。 我使用的是Visual Basic .Net 2010。

我最初在VBS中找到了以下代码并移植到VBA并且运行良好。如果我尝试在VB.NET 2010中使用相同的代码,即使我手动输入,也会出现多个错误并找不到LDAP路径。

Function FindUser()
 On Error GoTo Err

 Dim objRoot As Variant
 Dim LDAPdomainName As String
 Dim UserName As String
 Dim UserDomain As String

 Dim cn As Variant
 Dim cmd As Variant
 Dim rs As Variant


UserName = VBA.Environ("UserName") ' Gets Current User
UserDomain = VBA.Environ("UserDomain") 'Gets Current User's Domain


Set objRoot = GetObject("LDAP://RootDSE")
Domain= objRoot.Get("defaultNamingContext") 



 Set cn = CreateObject("ADODB.Connection")
 Set cmd = CreateObject("ADODB.Command")
 Set rs = CreateObject("ADODB.Recordset")

 cn.Open "Provider=ADsDSOObject;"

 cmd.activeconnection = cn
 'cmd.commandtext = "SELECT ADsPath FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'"
 'To see all attributes names available, connect with Active Directory Explorer and add to Select.
 cmd.commandtext = "SELECT cn, mail  FROM 'LDAP://" & Domain & "' WHERE sAMAccountName = '" & UserName & "'"
 Set rs = cmd.Execute


 Do Until rs.EOF
    Debug.Print rs("cn") & " E-mail: " & rs("mail")
    rs.MoveNext
 Loop


Exit_Err:
 If Not rs Is Nothing Then rs.Close
 If Not cn Is Nothing Then cn.Close
 Set rs = Nothing
 Set cmd = Nothing
 Set cn = Nothing
 Exit Function

Err:
 If Err <> 0 Then
    MsgBox "Error connecting to Active Directory Database: " & Err.Description
 Else
    If Not rs.BOF And Not rs.EOF Then
        rs.MoveFirst
        MsgBox rs(0)
    Else
        MsgBox "Not Found"
    End If
 End If
 Resume Exit_Err


End Function

4 个答案:

答案 0 :(得分:3)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain)

' find a user
Dim user As UserPrincipal = UserPrincipal.FindByIdentity(ctx, "domain\username")

' do something here....     
If user IsNot Nothing Then
End If

' find the group in question
Dim group As GroupPrincipal = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere")

' if found....
If group IsNot Nothing Then
    ' iterate over members
    For Each p As Principal In group.GetMembers()
            ' do whatever you need to do to those members
        Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName)
    Next
End If

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

答案 1 :(得分:3)

怎么样:

  

Imports System.DirectoryServices.AccountManagement

     

Dim userFullName As String = UserPrincipal.Current.DisplayName

答案 2 :(得分:1)

我有两个功能帮助我从.Net 2.0一直到.Net 4.0 快速浏览一下MSDN后, 可以在.Net运行时的所有版本中运行。

这两个功能是:


'Determines your domain name
Private Function DomainName() As String
    Dim objRootDSE As New System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    DomainName = objRootDSE.Properties("defaultNamingContext")(0)
End Function

'Will output user first name and last name. 
Public Sub ReturnUserName(ByVal UserAccountName As String)
    ' add a reference to System.DirectoryServices.dll
    Dim srch As System.DirectoryServices.DirectorySearcher
    Dim result As System.DirectoryServices.SearchResult
    Dim de, dir As System.DirectoryServices.DirectoryEntry

    de = New System.DirectoryServices.DirectoryEntry("LDAP://" & DomainName())
    srch = New System.DirectoryServices.DirectorySearcher(de)

    srch.SearchScope = SearchScope.Subtree
    srch.PropertiesToLoad.Add("givenName")
    srch.PropertiesToLoad.Add("sn")

    'Other field examples:
    'srch.PropertiesToLoad.Add("distinguishedName")
    'srch.PropertiesToLoad.Add("uid")

    ' users require both "user" and "person" filters
    ' and we also add the sAMAccountName to get the user passed.
    ' If you want to return all users in the domain remove the (sAMAccountName=" & UserAccountName & ")
    ' from the filter below.
    srch.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" & UserAccountName & "))"

    For Each result In srch.FindAll()
        dir = result.GetDirectoryEntry
        ' Properties are case sensitive!
        Debug.WriteLine(dir.Properties("givenname").Value & " " & dir.Properties("cn").Value)
    Next
End Sub

对此的一个示例调用是:


Public Sub TestUserCall()
    'Returns the current logged in user.
    Call ReturnUserName(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
End Sub

此示例调用将在运行时版本2.0到4.0中运行,并且在目前为止发布的所有版本中都能正常工作。

相关的MSDN页面是:

http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.name(v=VS.100).aspx

http://msdn.microsoft.com/en-us/library/94se97ay(v=VS.80).aspx

http://msdn.microsoft.com/en-US/library/system.directoryservices.directoryentry(v=VS.80).aspx

http://msdn.microsoft.com/en-US/library/system.directoryservices.searchresult(v=VS.80).aspx

答案 3 :(得分:0)

您可以使用System.DirectoryServices命名空间来执行此类任务(DirectoryServices是LDAP的托管包装器。)

Try
   ' Bind to the users container.
    Dim entry As New 
          DirectoryEntry("LDAP://CN=users,DC=fabrikam,DC=com")

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Create a SearchResultCollection object to hold a collection
    ' of SearchResults returned by the FindAll method.
    Dim result As SearchResultCollection = mySearcher.FindAll()

    ' Create an object to hold a single result from the 
    ' result collection.
    Dim resEnt1 As SearchResult

    ' Get search results. For more information, 
    ' see Getting Search Results.
    ' 
    ' This sample uses Try...Catch to catch errors.
    ' Create an Exception object. For more information, 
    ' see System.Exception.

Catch Exception1 As System.Runtime.InteropServices.COMException
    Console.WriteLine(Exception1.Message)

Catch Exception2 As InvalidOperationException
    Console.WriteLine(Exception2.Message)

Catch Exception3 As NotSupportedException
    Console.WriteLine(Exception3.Message)

End Try 

您可以使用search string,例如"(&(objectCategory=user)(objectClass=person)(sAMAccountName=" + userId + "))"search for a user(用户ID需要替换为用户ID)。

要将它们组合在一起,您可以修改下面的代码段,以便为用户提取all of the properties。然后,您可以将其调整为仅关注用户名。

Dim results As SearchResultCollection = Nothing

Try
    ' Bind to the users container.
    Dim path As String = "LDAP://CN=users,DC=fabrikam,DC=com"
    path = "LDAP://CN=Users,DC=strohmadom,DC=nttest,DC=microsoft,DC=com"
    Dim entry As New DirectoryEntry(path)

    ' Create a DirectorySearcher object.
    Dim mySearcher As New DirectorySearcher(entry)

    ' Set a filter for users with the name test.
    mySearcher.Filter = "(&(objectClass=user)(anr=test*))"

    ' Use the FindAll method to return objects to a SearchResultCollection.
    results = mySearcher.FindAll()

    ' Iterate through each SearchResult in the SearchResultCollection.
    Dim searchResult As SearchResult
    For Each searchResult In results
        ' Display the path of the object found.
        Console.WriteLine("Search properties for {0}", _
            searchResult.Path)

        ' Iterate through each property name in each SearchResult.
        Dim propertyKey As String
        For Each propertyKey In searchResult.Properties.PropertyNames
            ' Retrieve the value assigned to that property name 
            ' in the ResultPropertyValueCollection.
            Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)

            ' Iterate through values for each property name in each SearchResult.
            Dim propertyValue As Object
            For Each propertyValue In valueCollection
                ' Handle results. Be aware that the following 
                ' WriteLine() only returns readable results for 
                ' properties that are strings.
                Console.WriteLine("{0}:{1}", _
                    propertyKey, _
                    propertyValue.ToString())
            Next propertyValue
        Next propertyKey
    Next searchResult
Finally
    ' To prevent memory leaks, always call 
    ' SearchResultCollection.Dispose() manually.
    If Not results Is Nothing Then
        results.Dispose()
        results = Nothing
    End If
End Try