如何判断我的进程是否以管理员身份运行? [英] How can I tell if my process is running as Administrator?
问题描述
我想在进程以管理员身份运行时显示一些额外的 UI 元素,而不是在不以管理员身份运行时,类似于 Visual Studio 2008 在以管理员身份运行时在其标题栏中显示管理员"的方式.我怎么知道?
I would like to display some extra UI elements when the process is being run as Administrator as opposed to when it isn't, similar to how Visual Studio 2008 displays 'Administrator' in its title bar when running as admin. How can I tell?
推荐答案
从技术上来说,如果你想查看成员是否是本地管理员帐户,那么你可以得到安全标识符 (SID) 通过 User
属性 位于 WindowsIdentity
类,像这样(静态 GetCurrent
方法 获取当前 Windows 用户):
Technically, if you want to see if the member is the local administrator account, then you can get the security identifier (SID) of the current user through the User
property on the WindowsIdentity
class, like so (the static GetCurrent
method gets the current Windows user):
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
string sid = windowsIdentity.User.ToString();
User
属性返回用户的 SID,有许多预定义的不同组和用户的价值.
The User
property returns the SID of the user which has a number of predefined values for various groups and users.
然后你会检查是否SID 有以下模式,表示是本地管理员账户(这是一个众所周知的 SID)一个>:
S-1-5-{其他 SID 部分}-500
S-1-5-{other SID parts}-500
或者,如果您不想解析字符串,可以使用 SecurityIdentifier
类:
Or, if you don't want to parse strings, you can use the SecurityIdentifier
class:
// Get the built-in administrator account.
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid,
null);
// Compare to the current user.
bool isBuiltInAdmin = (windowsIdentity.User == sid);
但是,我怀疑您真正想知道的是当前用户是否是本地计算机管理员组的成员.您可以使用 WellKnownSidType
:BuiltinAdministratorsSid
的代码>
However, I suspect that what you really want to know is if the current user is a member of the administrators group for the local machine. You can get this SID using the WellKnownSidType
of BuiltinAdministratorsSid
:
// Get the SID of the admin group on the local machine.
var localAdminGroupSid = new SecurityIdentifier(
WellKnownSidType.BuiltinAdministratorsSid, null);
然后你可以查看用户的
属性,以查看该用户是否是本地管理员组的成员,如下所示:WindowsIdentity
上的 Groups
Then you can check the Groups
property on the WindowsIdentity
of the user to see if that user is a member of the local admin group, like so:
bool isLocalAdmin = windowsIdentity.Groups.
Select(g => (SecurityIdentifier) g.Translate(typeof(SecurityIdentifier))).
Any(s => s == localAdminGroupSid);
这篇关于如何判断我的进程是否以管理员身份运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!