C# 让程序自动以管理员身份运行

C# 让程序自动以管理员身份运行
2011年07月28日 19:05 来源:Lemon_s的博客 作者:Lemon_s 编辑:胡铭娅

  选中"Security",在界面中勾选"Enable ClickOnce Security Settings"后,在Properties下就有自动生成app.manifest文件。

  打开app.manifest文件,将

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

  改为

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

  修改后的app.manifest为:

<? xml version="1.0" encoding="utf-8" ?>
< asmv1:assembly manifestVersion ="1.0" xmlns ="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1 ="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2 ="urn:schemas-microsoft-com:asm.v2" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" >
< assemblyIdentity version ="1.0.0.0" name ="MyApplication.app" />
< trustInfo xmlns ="urn:schemas-microsoft-com:asm.v2" >
< security >
< requestedPrivileges xmlns ="urn:schemas-microsoft-com:asm.v3" >
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
If you want to utilize File and Registry Virtualization for backward
compatibility then delete the requestedExecutionLevel node.
-->
< requestedExecutionLevel level ="requireAdministrator" uiAccess ="false" />
</ requestedPrivileges >
< applicationRequestMinimum >
< defaultAssemblyRequest permissionSetReference ="Custom" />
< PermissionSet class ="System.Security.PermissionSet" version ="1" Unrestricted ="true" ID ="Custom" SameSite ="site" />
</ applicationRequestMinimum >
</ security >
</ trustInfo >
</ asmv1:assembly >

  然后在"Security"中再勾去"Enable ClickOnce Security Settings"后,重新编译即可。

C#中,要使得一个可执行文件(.exe)自动管理员模式运行,可以通过修改应用程序的清单文件来实现。这需要在程序集清单中设置请求执行级别的标志,这样当用户尝试运行程序时,Windows会提示用户以管理员权限运行。 以下是实现步骤: 1. 找到或创建你的应用程序的清单文件(通常是一个名为`yourapp.exe.manifest`的文件)。如果你的应用是编译后的,清单文件可能已经嵌入到可执行文件中。 2. 在清单文件中添加以下XML段落,以请求管理员权限: ```xml <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> ``` 这个`requestedExecutionLevel`节点的`level`属性被设置为`requireAdministrator`,这意味着每次运行程序时,系统都会提示用户以管理员权限运行。 3. 你需要确保你的应用程序的清单文件被正确地与可执行文件关联。如果你有清单文件的物理副本,可以使用Visual Studio中的manifest工具或其他清单编辑工具将清单文件嵌入到.exe文件中。 4. 编译应用程序后,当你尝试运行.exe文件时,Windows会自动检测到清单文件中的请求,并提示用户提升权限。 请注意,这可能要求你的应用程序符合运行管理员模式的特定标准,例如不能在Windows Vista或更高版本的用户账户控制(UAC)环境中无提示地运行。此外,某些操作系统安全策略可能限制这种行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值