2017-10-12 24 views
0

这一小段代码获取登录的用户的显示名称的系统当前获取账户管理 - 显示名称 - Vb.net

Imports System.DirectoryServices.AccountManagement 

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

上面的代码工作正常,当我连接局域网内电脑。但当局域网被删除和WIFI连接它不起作用..有人可以指导解决这个问题?

+0

这只只要目录服务器可以联系工作。我猜想通过WIFI目录服务器无法访问。 – MatSnow

+0

任何解决方法,我可以不连接到局域网的显示名称? –

回答

0

只有在可以联系目录服务器的情况下,此方法才有效。
否则你会得到一个PrincipalServerDownException

作为解决方法,您可以在服务器可达时缓存displayname。

您可以将其缓存在My.Settings的内部。
创建用户作用域设置命名为cachedDisplayname,并使用下面的方法:

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 

设置标签文本:

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