windows 管理运行权限测试申请

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6099080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:54:36  来源:igfitidea点击:

Testing application for Administrative Running Rights

windowsvb.netuac

提问by Axe

I want a sure-shot method to test if the application was run via the UAC box and has full administrative rights. Earlier, I thought of making a folder in C:\Windows\ for testing but running it on other computers proved to be a failure!

我想要一种可靠的方法来测试应用程序是否通过 UAC 框运行并具有完全管理权限。之前想过在C:\Windows\下建一个文件夹进行测试,结果在其他电脑上运行失败!

The UAC box provides all administrative rights to the computer to do anything(including making folders and creating files in places which needs there rights) and also makes sure that any child program so called or created also does have the same rights as the parent.

UAC 框为计算机提供了执行任何操作的所有管理权限(包括在需要权限的地方创建文件夹和创建文件),并确保任何所谓或创建的子程序也与父程序具有相同的权限。

Is there a sure-shot way to test if my application has been provided all the administrative rights that I can maximum get by the user while running the application or not? If yes, I would be glad to have to piece of code-work!

是否有可靠的方法来测试我的应用程序是否已获得用户在运行应用程序时可以获得的所有管理权限?如果是的话,我很高兴有一段代码工作!

回答by Dennis Traub

C#:

C#:

using System.Security.Principal;

...

var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

VB.Net:

VB.Net:

Imports System.Security.Principal

...

Dim identity = WindowsIdentity.GetCurrent()
Dim principal = new WindowsPrincipal(identity)
Dim isElevated as Boolean = principal.IsInRole(WindowsBuiltInRole.Administrator)

回答by SteveCinq

After a fair bit of poking around, I found that the most common solutions to this question return false negatives if the user's UAC is set to anything but Off.

经过一番摸索,我发现如果用户的 UAC 设置为除Off 以外的任何内容,则此问题的最常见解决方案会返回假阴性。

My solution these days is to do this:

我这些天的解决方案是这样做:

Imports System.Security.Principal
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Imports Microsoft.VisualBasic.ApplicationServices

''' <summary>Checks whether the current user is belongs to any Administrators groups.</summary>
''' <param name="AuthGroups">Optional. A flag indicating whether to use GetAuthorizationGroups instead of the - faster - GetGroups. Default=true.</param>
''' <returns>True if the user belongs to an Administrators group, false otherwise.</returns>
Public Function IsAdministrator(
    Optional ByVal AuthGroups As Boolean = True) As Boolean

    Static bResult As Boolean? = Nothing
    Try
        If bResult Is Nothing Then
            bResult = New WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)
            If Not bResult Then
                Dim oContext As PrincipalContext = Nothing
                Try 'Domain check first
                    Domain.GetComputerDomain()
                    oContext = New PrincipalContext(ContextType.Domain)
                Catch
                    'Fall through to machine check
                End Try
                If oContext Is Nothing Then oContext = New PrincipalContext(ContextType.Machine)
                'Dim oPrincipal As UserPrincipal = UserPrincipal.FindByIdentity(oContext, WindowsIdentity.GetCurrent().Name) ' Don't use - slow
                Using oSearchUser As Principal = New UserPrincipal(oContext)
                    oSearchUser.SamAccountName = WindowsIdentity.GetCurrent().Name
                    Using oSearcher As PrincipalSearcher = New PrincipalSearcher(oSearchUser)
                        Using oUser As Principal = oSearcher.FindOne()
                            If oUser IsNot Nothing Then
                                If AuthGroups Then
                                    bResult = CType(oUser, UserPrincipal).GetAuthorizationGroups().Any(Function(p) _
                                        p.Sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountDomainAdminsSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountEnterpriseAdminsSid))
                                Else
                                    bResult = oUser.GetGroups().Any(Function(p) _
                                        p.Sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountDomainAdminsSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) OrElse
                                        p.Sid.IsWellKnown(WellKnownSidType.AccountEnterpriseAdminsSid))
                                End If
                            End If
                        End Using
                    End Using
                End Using
            End If
        End If
    Catch
        bResult = False
    End Try
    Return bResult.GetValueOrDefault(False)
End Function

This method is a composite of a few other answers, so I only take credit for packaging it up into a function that will only ever run once and therefore if there is a bit of a delay due to the fall-through, you can probably hide it in start-up.

这种方法是其他一些答案的组合,所以我只相信将它打包成一个只会运行一次的函数,因此如果由于失败而有一点延迟,你可能可以隐藏它在启动。

The AuthGroupsargument gives you a choice of the more thorough, recursive AuthorizationGroupscheck (default) or the faster Groupscheck.

AuthGroups参数使您可以选择更彻底的递归AuthorizationGroups检查(默认)或更快的Groups检查。