Get the Current User’s Display Name

In an ASP.Net page you can easily get the username of the currently logged in user with Request.ServerVariables("AUTH_USER"). With the following code snippet you can also get their real name (the “Display Name”) from the Active Directory.

To use the following code you will need to be using .NET 2, access to the page in IIS must be controlled via Windows Authentication, and there must be a reference to the System.DirectoryServices in the Web.Config file. The function returns a string with the Display Name of the currently logged in user. This code is written in VB.NET.

    Function GetUserFullName() As String
        'Returns the Full Name (Display Name) of the domain user accessing this web page
        'Requires the User to be logged in using Windows Authentication
        'Also requires a reference to System.DirectoryServices (.NET 2)
        Try
            Dim dEntry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry("WinNT://" + Request.ServerVariables("AUTH_USER").Replace("", "/"))
            Return dEntry.Properties("fullName").Value.ToString
        Catch
            Return ""
        End Try
    End Function

Advert:

Leave a Reply

Your email address will not be published. Required fields are marked *