在有些情况下,您可能需要获取当前的Windows用户信息,通过使用WindowsIdentity类,VB.NET可以帮助您简化这一过程。在这篇技巧中,我将展示如何用WindowsIdentity类及其属性来访问当前用户信息。
WindowsIdentity类
在名域空间System.Security.Principal下的WindowsIdentity类可以展示一些关于Windows账户的基本信息。WindowsIdentity.GetCurrent方法允许您在当前运行的代码中获取WindowsIdentity对象,在列表A中,我使用了WindowsIdentity.GetCurrent方法来获取当前的用户信息。
列表A
Private Sub GetUserInfo()
Dim UserIdentityInfo As System.Security.Principal.WindowsIdentity
Dim strMsg As String
UserIdentityInfo = System.Security.Principal.WindowsIdentity.GetCurrent()
strMsg = "User Name: " & UserIdentityInfo.Name & vbCrLf
strMsg = strMsg & " Token: " & UserIdentityInfo.Token.ToString() & vbCrLf
strMsg = strMsg & " Authenticated: " & UserIdentityInfo.AuthenticationType & vbCrLf
strMsg = strMsg & " System: " & UserIdentityInfo.IsSystem & vbCrLf
strMsg = strMsg & " Guest: " & UserIdentityInfo.IsGuest & vbCrLf
strMsg = strMsg & " Anonymous: " & UserIdentityInfo.IsAnonymous & vbCrLf
MessageBox.Show(strMsg)
End Sub
在上述的例子中,我将UserIdetityInfo定义为一个WindowsIdentity类,我还定义了字符串变量strMsg来存放信息,并在最后进行显示。通过使用WindowsIdentity类的GetCurrent方法,我将变量UserIdentityInfo的值设定为当前用户。最后,我使用了UserIdentityInfo的各种属性,并将它们连接为一个字符串值(存储在strMsg中)然后显示在消息框中。
责任编辑:张琎
用户评论