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

有些代码操作需要取得管理员权限,不如把整个程序设置为以管理员运行。

C#程序设置以管理员权限运行,比较简单:

1. 为项目添加manifest文件(已添加的则跳过)。

2.  requestedExecutionLevel 设置为 requireAdministrator

<!--
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

问题解决。exe文件已打上管理员权限的图标:

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

小鹰信息技术服务部

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值