C#程序以管理员权限运行

文章介绍了在Vista及更高版本的Windows操作系统中,如何在C#程序中处理UAC用户账户控制机制,当需要管理员权限运行时,提供了三种方法:一是通过System.Diagnostics.Process.Start()启动;二是添加应用程序清单文件并修改执行级别;三是直接修改程序文件属性。这些方法使得开发者无需强制用户关闭UAC,也能在需要时以管理员权限运行应用。
摘要由CSDN通过智能技术生成

在Vista 和 Windows 7 及更新版本的操作系统,增加了 UAC(用户账户控制) 的安全机制,如果 UAC 被打开,用户即使以管理员权限登录,其应用程序默认情况下也无法对系统目录、系统注册表等可能影响系统正常运行的设置进行写操作。这个机制大大增强了系统的安全性,但对应用程序开发者来说,我们不能强迫用户去关闭UAC,但有时我们开发的应用程序又需要以 Administrator 的方式运行,如何实现这样的功能呢?

下面演示 C# 程序如何实现提示用户以管理员权限运行。

本例以WinForm程序演示,新建一项目生成后进行相应修改:

方法一:通过 System.Diagnostics.Process.Start() 方式启动:

实现方法: 修改默认生成的Program文件,修改后的代码如下:

由于已经在代码上做了注释,所以不再详细说明;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsUACRunAsAdministrator
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //在Vista 和 Windows 7 及更新版本的操作系统,增加了 UAC(用户账户控制) 的安全机制,如果 UAC 被打开,用户即使以管理员权限登录,其应用程序默认情况下也无法对系统目录、系统注册表等可能影响系统正常运行的设置进行写操作。这个机制大大增强了系统的安全性,但对应用程序开发者来说,我们不能强迫用户去关闭UAC,但有时我们开发的应用程序又需要以 Administrator 的方式运行,如何实现这样的功能呢?
            //下面演示 C# 程序如何实现提示用户以管理员权限运行。
            //本例以WinForm程序演示,新建一项目生成后进行相应修改:

            //方法一:通过 System.Diagnostics.Process.Start() 方式启动:
            // 获取当前的windows 用户
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            //检查 获取当前的windows 用户 的 Windows 组成员身份。
            System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(identity);
            //确定当前主体是否属于具有指定 System.Security.Principal.WindowsBuiltInRole 的 Windows 用户组。
            //判断当前用户是否是管理员
            if (windowsPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                MessageBox.Show($"{identity.Name}是管理员角色,管理员权限运行");
                //是管理员角色,管理员权限运行
                Application.Run(new Form1());
            }
            else
            {
                //创建启动对象
                ProcessStartInfo processStartInfo= new ProcessStartInfo();
                processStartInfo.UseShellExecute = false;
                //processStartInfo.RedirectStandardOutput = true;
                //processStartInfo.RedirectStandardError = true;
                //processStartInfo.RedirectStandardInput = true;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
                processStartInfo.FileName = Application.ExecutablePath;
                //设置启动动作确保 使用管理员权限运行
                processStartInfo.Verb = "runas";
                try
                {
                    Process.Start(processStartInfo);
                }
                catch (Exception)
                {
                    return;
                }
                //退出
                Application.Exit();
            }

            //方法二:通过添加应用程序清单文件:
            //在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮
            //添加后,默认打开app.manifest文件,将:
            //< requestedExecutionLevel  level = "asInvoker" uiAccess = "false" />
            //修改为:
            //< requestedExecutionLevel level = "requireAdministrator" uiAccess = "false" />
            //然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。
            //项目属性 => 应用程序 => 资源 => 清单 => app.manifest。
            //重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。
            //需要注意的是:如果在VS中 启动调试 的话,就会提示 此任务要求应用程序具有提升的权限。如下图:
        }

        /// <summary>
        /// 确定当前主体是否属于具有指定 Administrator 的 Windows 用户组
        /// </summary>
        /// <returns>如果当前主体是指定的 Administrator 用户组的成员,则为 true;否则为 false。</returns>
        public static bool IsAdministrator()
        {
            bool result;
            try
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                result = principal.IsInRole(WindowsBuiltInRole.Administrator);

                //http://www.cnblogs.com/Interkey/p/RunAsAdmin.html
                //AppDomain domain = Thread.GetDomain();
                //domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                //WindowsPrincipal windowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
                //result = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                result = false;
            }
            return result;
        }
    }
}

效果:由于是通过System.Diagnostics.Process.Start() 方式外部调用启动,所以直接通过VS运行时,是不会提示VS也需要管理员权限,只有程序本身需要管理员权限,与生成应用程序的程序不同。这点是和方法二实现的主要不同之处。

本文地址:C#程序以管理员权限运行 - Cosmic_Spy - 博客园

方法二:通过添加应用程序清单文件:

在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮

添加后,默认打开app.manifest文件,将:

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

修改为:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。

重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。

需要注意的是:如果在VS中 启动调试 的话,就会提示 此任务要求应用程序具有提升的权限。如下图:

判断程序是否以管理员身份运行

 需要添加命名空间:

using System.Security.Principal;

/// <summary>
    /// 确定当前主体是否属于具有指定 Administrator 的 Windows 用户组
    /// </summary>
    /// <returns>如果当前主体是指定的 Administrator 用户组的成员,则为 true;否则为 false。</returns>
    public static bool IsAdministrator()
    {
        bool result;
        try
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            result = principal.IsInRole(WindowsBuiltInRole.Administrator);

            //http://www.cnblogs.com/Interkey/p/RunAsAdmin.html
            //AppDomain domain = Thread.GetDomain();
            //domain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            //WindowsPrincipal windowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
            //result = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch
        {
            result = false;
        }
        return result;
    }

方法三:直接修改程序文件的属性

右击程序文件,在弹出的属性对话框中的 兼容性 标签页中

勾选“以管理员身份运行此程序”即可。

 

如果有兴趣还可以继续查看下面的链接:

C# 让程序自动以管理员身份运行 - Lemon_s - 博客园

转载:编写C#程序让其在Win7 下以管理员权限运行 - 慧由心生 - 博客园

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#程序中请求管理员权限可以通过在app.manifest文件中设置请求管理员权限,或者使用代码请求管理员权限。 方法一:在app.manifest文件中设置请求管理员权限 在项目中的app.manifest文件中,找到下面的代码块,并将requestedExecutionLevel的level属性设置为requireAdministrator。 ```xml <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> ``` 方法二:使用代码请求管理员权限 使用代码请求管理员权限需要使用Windows API函数,可以使用下面的代码: ```csharp using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace AdminLauncher { class Program { [DllImport("user32.dll", SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetConsoleWindow(); static void Main(string[] args) { if (!IsAdmin()) { StartAsAdmin(); return; } // 操作管理员权限下的资源 } static bool IsAdmin() { var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); var principal = new System.Security.Principal.WindowsPrincipal(identity); return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); } static void StartAsAdmin() { var fileName = Process.GetCurrentProcess().MainModule.FileName; var startInfo = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = fileName, Verb = "runas" }; Process.Start(startInfo); ShowWindow(GetConsoleWindow(), 0); } } } ``` 以上代码中,IsAdmin方法用于判断当前程序是否以管理员权限运行,如果是,则执行管理员权限下的操作,否则调用StartAsAdmin方法以管理员权限重新启动程序。StartAsAdmin方法使用ProcessStartInfo对象来设置启动参数,其中Verb属性设置为"runas"表示以管理员权限启动程序。注意,使用Verb属性可能会弹出UAC提示框,需要用户授权才能继续执行,如果不想显示UAC提示框,可以使用Windows API函数ShowWindow将控制台窗口隐藏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值