c# - 如何判断我的进程是否以管理员身份运行?

标签 c# .net process privileges

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

最佳答案

从技术上讲,如果您想查看该成员是否是本地管理员帐户,那么您可以获得security identifier (SID)当前用户通过 User propertyWindowsIdentity class 上,像这样(静态 GetCurrent method 获取当前 Windows 用户):

WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

string sid = windowsIdentity.User.ToString();

User 属性返回用户的 SID has a number of predefined values for various groups and users .

然后你会检查是否the SID has the following pattern, indicating it is the local administrator account (which is a well-known SID) :

S-1-5-{other SID parts}-500

或者,如果你不想解析字符串,你可以使用 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 获取此 SID BuiltinAdministratorsSid:

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

然后你可以检查Groups property在用户的 WindowsIdentity 上查看该用户是否是本地管理员组的成员,如下所示:

bool isLocalAdmin = windowsIdentity.Groups.
    Select(g => (SecurityIdentifier) g.Translate(typeof(SecurityIdentifier))).
    Any(s => s == localAdminGroupSid);

关于c# - 如何判断我的进程是否以管理员身份运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/509292/

相关文章:

java - 如何获取我刚刚在 java 程序中启动的进程的 PID?

javascript - 使用 javascript 在 2 个 google chrome 进程(选项卡)之间进行通信

c# - 我可以使用 LINQ 从 Quickbooks Online ServiceContext 获取超过 100 条记录吗?

c# - 哪些行为驱动开发 (BDD) 工具/框架可用于 Microsoft Stack?

C# - 无法从 UDP 获取服务器响应 - Black Ops Rcon

c# - 我可以存储的 .NET 缓存 key 的限制是多少?

c - "Detaching after fork from child process 15***"的含义?

c# - 按值而非引用将 List<T> 分配给另一个 List<T>

c# - 在 List<entity> 中搜索具有类属性匹配值的记录?

c# - 互操作程序集中的名称大写错误