Get Account management - Display Name - Vb.net

时间:2017-10-12 09:45:21

标签: vb.net

This little piece of code gets the system current logged in user's Display name

Imports System.DirectoryServices.AccountManagement

Dim userFullName As String = UserPrincipal.Current.DisplayName
Label1.Text = "Hi " & userFullName & ", Welcome !!"

The above code works fine when i connected the LAN to the computer. but when LAN is removed and WIFI is connected it doesn't work .. Can someone guide the workaround for this?

1 个答案:

答案 0 :(得分:0)

This method only works as long as the directory server can be contacted.
Otherwise you get a PrincipalServerDownException.

As a workaround you could cache the displayname while the server is reachable.

You can cache it for example inside My.Settings.
Create a user scoped setting named cachedDisplayname and use the following method:

Function GetUserDisplayName() As String
    Dim userFullName As String

    Try
        'Reading the displayname from the directory
        userFullName = UserPrincipal.Current.DisplayName
        'Saving the displayname in My.Settings
        My.Settings.cachedDisplayname = userFullName
        My.Settings.Save()
    Catch ex As PrincipalServerDownException
        If String.IsNullOrWhiteSpace(My.Settings.cachedDisplayname) Then
            'displayname has not been cached yet, use Username as compromise solution
            userFullName = Environment.UserName
        Else
            'read the cached displayname from My.Settings
            userFullName = My.Settings.cachedDisplayname
        End If
    End Try

    Return userFullName
End Function

Setting the label-text:

Label1.Text = String.Format("{0}, Welcome !!", GetUserDisplayName())