只有在可以聯繫目錄服務器的情況下,此方法纔有效。
否則你會得到一個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
任何解決方法,我可以不連接到局域網的顯示名稱? –