vs2005 ,2008,2010中引入app.manifest(即c#程序在win7下以管理员权限运行方法)

千行

关注

阅读 48

2022-06-29

 打开VS2005、VS2008、VS2010工程,查看工程文件夹中的Properties文件夹下是否有app.manifest这个文件;如没有,按如下方式创建:鼠标右击工程在菜单中选择“属性”,点击工程属性的“安全性”标签,在安全性标签页中勾选“启用ClickOnce安全设置”,并选择“这是完全可信的应用程序”,保存工程,此时在Properties下已经自动生成了app.manifest文件。

        将默认的app.manifest文件修改为

[html] view plain copy

 

<?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>
</security>
</trustInfo>
</asmv1:assembly>

 

        配置文件修改后,我们运行应用程序,就会首先弹出这样一个提示框,点 Yes 后,程序才可以继续运行。

        顺便说下,还可以通过一个方法了解到此时程序运行是不是管理员权限:

 

[csharp] view plain copy

public static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

 对于XML文件中引用的UAC执行权限级别,分别代表下列含义:

 

         asInvoker : 应用程序就是以当前的权限运行。

         highestAvailable: 这个是以当前用户可以获得的最高权限运行。

         requireAdministrator: 这个是仅以系统管理员权限运行。

         默认情况下是 asInvoker。

         highestAvailable 和 requireAdministrator 这两个选项都可以提示用户获取系统管理员权限。那么这两个选项的区别在哪里呢?

         他们的区别在于,如果我们不是以管理员帐号登录,那么如果应用程序设置为 requireAdministrator ,那么应用程序就直接运行失败,无法启动。而如果设置为 highestAvailable,则应用程序可以运行成功,但是是以当前帐号的权限运行而不是系统管理员权限运行。如果我们希望程序在非管理员帐号登录时也可以运行(这种情况下应该某些功能受限制) ,那么建议采用 highestAvailable 来配置。

 

龙腾一族至尊龙骑

精彩评论(0)

0 0 举报