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

工具:VS 2008

 

第一步,

      新建一个项目(winform)

 

第二步,

      在新建项目中,新建项 应用程序清单文件(app.manifest)

 

第三步,

      打开 app.manifest 文件

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

          修改为 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

          重新编译 打开 debug目录 就可以看到图标右下角有个小盾牌的标识。

整个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 清单选项
            如果希望更改 Windows 用户帐户控制级别,请用以下节点之一替换
            requestedExecutionLevel 节点。

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

            如果您希望利用文件和注册表虚拟化提供
            向后兼容性,请删除 requestedExecutionLevel 节点。
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>
</asmv1:assembly>

第四步,

      程序中判断是否以管理员身份运行

代码如下:

C#代码  
/// <summary>
/// 当前是否是管理员身份运行
/// </summary>
/// <returns></returns>
public static bool IsAdministrator()
{
    try
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch
    {
        return true;
    }
}

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
发出的红包

打赏作者

random_2011

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

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

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

打赏作者

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

抵扣说明:

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

余额充值