我怎么知道我的进程是否以管理员身份运行?

问题描述 投票:32回答:5

我想在以管理员身份运行该进程时显示一些额外的UI元素,而不是以非管理员身份显示,这类似于Visual Studio 2008以管理员身份运行时在其标题栏中显示“管理员”的方式。我怎么知道?

c# .net process privileges
5个回答
34
投票
从技术上讲,如果要查看成员是否是本地管理员

帐户,则可以通过security identifier (SID)上的User property获取当前用户的User,就像这样(静态WindowsIdentity class获取当前的Windows用户):

WindowsIdentity
GetCurrent method属性返回GetCurrent的用户的SID。

然后您将检查是否WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent(); string sid = windowsIdentity.User.ToString();

S-1-5- {其他SID部件} -500

或者,如果您不想解析字符串,则可以使用User类:

has a number of predefined values for various groups and users

但是,我怀疑您

真正

想知道的是当前用户是否是本地计算机的管理员group的成员。您可以使用the SID has the following pattern, indicating it is the local administrator account (which is a well-known SID)SecurityIdentifier获取此SID:SecurityIdentifier
然后您可以在用户的​​// Get the built-in administrator account.
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, 
    null);

// Compare to the current user.
bool isBuiltInAdmin = (windowsIdentity.User == sid);
上检查WellKnownSidType,以查看该用户是否是本地管理员组的成员,如下所示:

WellKnownSidType


21
投票
我认为这是一个很好的简单机制。

BuiltinAdministratorsSid


4
投票
这里是一个班轮。

// Get the SID of the admin group on the local machine. var localAdminGroupSid = new SecurityIdentifier( WellKnownSidType.BuiltinAdministratorsSid, null);


0
投票
我感到很重要,请注意上述每个casperOne的答案在尝试使用WellKnownSidType.BuiltinAdministratorsSid时遇到的困难。根据Groups property,BuiltinAdministratorsSid“指示与管理员帐户匹配的SID”。因此,我希望casperOne的代码能够正常工作,并且猜测它可能在某些环境中也可以。不幸的是,我的Windows 2003上没有.NET 2.0(旧版代码)。它实际上返回了S-1-5-32-544,根据Groups,它是管理员

group的sid。因此,比较对我而言是失败的。我将不得不对以“ S-1-5-21”开头的字符串进行自己的字符串比较(即使上面提到的博客没有,kb 243330表示包括“ 21”),并且以“ 500”结尾。


-1
投票
我使用简单的try catch语句在

“ C:\ Windows \”文件夹中创建一个随机文件。如果出现错误,则该应用程序将以普通特权运行,否则将以管理员特权运行。

WindowsIdentity
© www.soinside.com 2019 - 2024. All rights reserved.