c#如何判断winform程序是否有管理员权限

c#如何判断winform程序是否有管理员权限

c#如何判断winform程序是否有管理员权限

这可以通过Windows的System.Security.Principal类轻松完成。
system.security.principal命名空间定义了一个主体对象,该对象表示代码运行所处的安全上下文。导入此类时,可以访问命名空间的WindowsIdentity类。此类表示运行应用程序的当前用户。
使用此对象,可以检查当前标识是否与Windows用户的Windows组成员身份匹配,在本例中是管理员角色。提供作为WindowsPrincipal类的新实例的第一个参数。从该对象中,可以调用IsInRole方法来验证是否为管理员:

using System.Security.Principal;

// Store boolean flag
bool isAdmin;

using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
    WindowsPrincipal principal = new WindowsPrincipal(identity);

    // If is administrator, the variable updates from False to True
    isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}

// Check with a simple condition whether you are admin or not
if (isAdmin)
{
    MessageBox.Show("You have administrator rights !");
}
else
{
    MessageBox.Show("You don't have administrator rights :C !");
}

你可以将他封装成一个方法

using System.Security.Principal;

/// <summary>
/// Boolean method that verifies if the current user has administrator rights.
/// </summary>
/// <returns></returns>
public bool IsAdministrator()
{
    bool isAdmin;

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

    return isAdmin;
}
You can use it with a conditional:

if (this.IsAdministrator())
{
    MessageBox.Show("You have administrator rights !");
}
else
{
    MessageBox.Show("You don't have administrator rights :C !");
}

ok,完成了

{{collectdata}}

网友评论0