未连接时处理AD错误

时间:2014-11-19 11:28:48

标签: vb.net active-directory directoryservices

我使用以下代码获取logge don用户的登录名。连接到网络/域时,此工作正常。但是当离线时,我在第3行遇到错误:

PrincipalServerDownException未处理

无法联系服务器。

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

如何检查并向用户返回用户错误,例如" Not on network"或"未连接到域",然后退出?我已尝试过以下内容,但这只是出错:

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

1 个答案:

答案 0 :(得分:0)

使用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