/ / Obsługa błędów AD, gdy nie są połączone - vb.net, active-directory, directoryservices

Obsługa błędów AD, gdy nie są połączone - vb.net, active-directory, directoryservices

Używam poniższego kodu, aby uzyskać nazwę logowania użytkownika log don. Działa to dobrze po podłączeniu do sieci / domeny. Ale w trybie offline pojawia się błąd w trzeciej linii:

Wyjątek PrincipalServerDownException był nieobsługiwany

Nie można skontaktować się z serwerem.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
Label5.Text = DisplayName
Label4.Text = GetUserProperties()
End Sub

Jak mogę to sprawdzić i zwrócić użytkownikowi błąd, na przykład "Nie w sieci" lub "brak połączenia z domeną", a następnie zakończyć? Próbowałem poniżej, ale to daje ten sam błąd:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
If System.DirectoryServices.AccountManagement.UserPrincipal.Current Is Nothing Then
MsgBox("Network Error: No Connection to Domain")
Application.Exit()
Else ....
End if
End Sub

Odpowiedzi:

0 dla odpowiedzi № 1

Użyj try / catch

    Try
Dim currentADUser As System.DirectoryServices.AccountManagement.UserPrincipal
currentADUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Dim DisplayName As String = currentADUser.GivenName & " " & currentADUser.Surname
Label5.Text = DisplayName
Label4.Text = GetUserProperties()
Catch ex As Exception
MsgBox(...)
End Try