The current Windows User is in the Administration

2019-09-05 08:45发布

问题:

I need to check if the current Logon Windows account is an Administrator of the PC.

If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
    'Is Admin
Else
    'Isn't Admin
End If

This code work fine but if i lunch the code with RUN AS "another account" the code dont do the right job becouse take the account that lunch the code not the Windows account that is logged in.

With this code i can see the current Windows User logged in:

Dim Coll As ManagementObjectCollection
Dim LogonName As String
Dim GetName As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Coll = GetName.[Get]()
LogonName = DirectCast(Coll.Cast(Of ManagementBaseObject)().First()("UserName"), String)
Dim CleanName() As String = Split(LogonName, "\")

So in the string LogonName i'll have the Windows user name account that is logged in but how can i check if is an Administrator?

回答1:

Just Try this

 Public Function isAdmin() As Boolean
    Dim isAdmin1 As Boolean
    Dim CurrUser As WindowsIdentity
    'this will gets the currently logged User
    CurrUser = WindowsIdentity.GetCurrent()
    '****************************************
    'this will checks the current user is  an administrative user
    Dim principal As New WindowsPrincipal(CurrUser)
    isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator)
    Return isAdmin
 End Function


Created On visual-studio-2008 (.net-3.5)



标签: vb.net admin