VB - Get FirstName & LastName from ActiveDirectory

By , 6/14/2012
(1 ratings)
If you need to retrieve user details on basis of windows user ID.You can use below code to get windows userID like
Dim username As String = theRequest.LogonUserIdentity.Name

Dim strName As String = username.Substring(0, username.IndexOf("\") + 1)
Dim length As Integer = strName.Length
username = username.Remove(0, length)

call method like

  Private Function GetActiveDirUserDetails(ByVal userid As String) As String
        Dim dirEntry As System.DirectoryServices.DirectoryEntry
        Dim dirSearcher As System.DirectoryServices.DirectorySearcher
        Dim domainName As String = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName
            dirEntry = New System.DirectoryServices.DirectoryEntry("LDAP://" & domainName)
            dirSearcher = New System.DirectoryServices.DirectorySearcher(dirEntry)
            dirSearcher.Filter = "(samAccountName=" & userid & ")"

            'Users e-mail address
            'Users last name
            Dim sr As SearchResult = dirSearcher.FindOne()
            If sr Is Nothing Then 'return false if user isn't found 
                Return False
            End If
            Dim de As System.DirectoryServices.DirectoryEntry = sr.GetDirectoryEntry()
            Dim userFirstLastName = de.Properties("sn").Value.ToString() + ", " + de.Properties("GivenName").Value.ToString()
            Return userFirstLastName
        Catch ex As Exception ' return false if exception occurs 
            Return ex.Message
        End Try
    End Function



Log in, to comment!