WPF 设置管理员权限启动

在 dotnet 程序,可以通过清单文件设置管理员权限启动

通过下面代码可以判断当前的程序是管理员权限运行

            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                // 当前正在以管理员权限运行。
            }

而设置软件启动权限是管理员权限可以添加清单文件,右击添加 App.manifest 文件,此时要求在 csproj 设置 <ApplicationManifest>App.manifest</ApplicationManifest> 才可以

  <PropertyGroup>
      <ApplicationManifest>App.manifest</ApplicationManifest>
  </PropertyGroup>

在 App.manifest 文件将 requestedPrivileges 替换下面代码

  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC 清单选项
             如果想要更改 Windows 用户帐户控制级别,请使用
             以下节点之一替换 requestedExecutionLevel 节点。n
        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
            如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
            元素。
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

 转自:https://cloud.tencent.com/developer/article/1584709

原文地址:https://www.cnblogs.com/javalinux/p/14440312.html