Looking Up a User in Active Directory - .Net Framework

The following VB.NET code demonstrates how to lookup a user in Active Directory. You can convert code between C# and VB.NET at this website.

Imports System.DirectoryServices
Imports System.DirectoryServices.ActiveDirectory


Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click

    Dim de As DirectoryEntry = New DirectoryEntry()
    Dim sUserQualifiedName As String = _
        System.Security.Principal.WindowsIdentity.GetCurrent.Name
    Debug.Print(GetUserFullName(sUserQualifiedName))

End Sub



Public Function GetUserFullName(ByVal userQualifiedName As _
String) As String

    Dim de As DirectoryEntry = Nothing
    Dim path As String
    Dim result As String

    Try
        path = "WinNT://" & userQualifiedName.Replace("\", "/")
        de = New DirectoryEntry(path)
        result = CType(de.Invoke("Get", "FullName"), String)
         If result.Contains(",") Then
            Dim pos As Integer = result.IndexOf(",")
            result = result.Substring(pos + 2) & " " & _
                        result.Substring(0, pos)
        End If

    Catch ex As Exception
        result = ""

    Finally
        de.Close()
        de.Dispose()

    End Try

    Return result

End Function


End Class