检查C#中的管理员权限

发布于 2024-11-06 13:45:53 字数 79 浏览 9 评论 0原文

我想知道程序是否以管理员身份运行。

用户不必是管理员。我只想知道我的应用程序是否有权编辑某些以管理员身份运行时可编辑的受保护文件。

I want to know if a program is running as administrator.

The user doesn't have to be administrator. I only want to know if my application has rights to edit some secured files that are editable when running as Administrator.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拥抱影子 2024-11-13 13:45:53

这将返回一个 bool valid

using System.Security.Principal;

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

This will return a bool valid

using System.Security.Principal;

bool isElevated;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
寒冷纷飞旳雪 2024-11-13 13:45:53

以下是 @atrljoe 的答案,使用最新的 C# 转换为单行代码:

using System.Security.Principal;

static bool IsElevated => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

Here's @atrljoe's answer turned into a one liner using the latest C#:

using System.Security.Principal;

static bool IsElevated => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
帅气尐潴 2024-11-13 13:45:53

为了避免 SecurityException 和泄漏,例如不关闭 WindowsIdentity.GetCurrent(),因为 WindowsPrincipal 不会显式关闭,而只会创建一个新连接然后才将其关闭。

private static bool IsAdministrationRules() {
   try {
       using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) {
          return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);
       }
   } catch {
       return false;
   }
}

To avoid SecurityException, and leaks, like not closing WindowsIdentity.GetCurrent(), since WindowsPrincipal does not explicitly close, but only creates a new connection and only then closes it.

private static bool IsAdministrationRules() {
   try {
       using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) {
          return (new WindowsPrincipal(identity)).IsInRole(WindowsBuiltInRole.Administrator);
       }
   } catch {
       return false;
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文