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

exe在Vista或Win7下不以管理员权限运行,会被UAC(用户帐户控制)阻止访问系统某些功能,如修改注册表操作等;如何让exe以管理员权限运行呢,方法有两种,一个是直接修改exe属性;另一个是在程序中加入MANIFEST资源,下面分别介绍。

 

1. 直接修改exe属性:

1) 右击“exe”,在弹出的菜单中选择“属性”,出现的界面如下图:

     

 

2) 选择"Compatibility"项,并勾选"Run this program as administrator"项即可。

 

2. 在程序中加入MANIFEST资源: 

1) 打开Vs2005或vs2008工程,看在Properties下是否有app.manifest这个文件;如没有,右击工程在菜单中选择“属性”,出现界面如下:

选中"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"后,重新编译即可。

 

posted on   Lemon_s  阅读(9547)  评论(2编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南

导航

< 2011年7月 >
26 27 28 29 30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6
点击右上角即可分享
微信分享提示