只有在可以联系目录服务器的情况下,此方法才有效。
否则你会得到一个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())
这只只要目录服务器可以联系工作。我猜想通过WIFI目录服务器无法访问。 – MatSnow
任何解决方法,我可以不连接到局域网的显示名称? –