如何强制 .NET 程序以 管理员模式 运行 ?

咨询区

  • Gold

我有一个 winform 程序部署客户的PC机上,请问我如何通过编码的形式强制让程序以管理员模式运行?

回答区

  • Gaspa79

如果你用的是 Visual Studio 2019,可以通过工具去配置,右键 项目 -> 新建项 -> Application Manifest File 。

图片

在 manifest 文件中,找到 requestedExecutionLevel 节点,它的 level 可以设置为如下三种。

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

如果要用管理员模式的话,使用 requireAdministrator 即可。

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

  • Gaspa79

如何因为某些原因你必须要通过 纯代码 解决的化,可以参考我的实现代码。

using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;

public static class AdminRelauncher
{
    public static void RelaunchIfNotAdmin()
    {
        if (!RunningAsAdmin())
        {
            Console.WriteLine("Running as admin required!");
            ProcessStartInfo proc = new ProcessStartInfo();
            proc.UseShellExecute = true;
            proc.WorkingDirectory = Environment.CurrentDirectory;
            proc.FileName = Assembly.GetEntryAssembly().CodeBase;
            proc.Verb = "runas";
            try
            {
                Process.Start(proc);
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
                Environment.Exit(0);
            }
        }
    }

    private static bool RunningAsAdmin() 
    {
        WindowsIdentity id = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(id);

        return principal.IsInRole(WindowsBuiltInRole.Administrator);             
    }
}

点评区

要想让程序以管理员模式运行,这篇就学习了两种方式,当在程序中需要操控一些系统资源或者第三方工具时,通常就需要以管理员模式的刚性需求啦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值