做过WPF/WinForm,或者Console的同学应该知道,如果我们是需要对C盘文件、注册表做操作,那么我们需要在.EXE运行起来之前获取Administrator权限,也就是俗话说的:以管理员权限运行,那么怎么让你的.EXE自动获取Administrator权限呢?(因为你不可能口头告诉你的客户,他花钱请你做的东西需要右击->”以管理员方式运行”)

非常简单,只需要添加app.manifest文件,然后修改: <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

但是,如果你使用VS2017,同时使用最新的*.csproj格式,编译的时候会报如下错误:

CS1926	Error opening Win32 manifest file D:\app.manifest -- Could not find file 'D:\app.manifest'.

奇怪,为什么会报这个错误呢?为了一探究竟,打开编辑*.csproj文件,

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net461</TargetFramework>
    <ApplicationManifest>\app.manifest</ApplicationManifest>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Topshelf" Version="4.0.3" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="System.Configuration" />
  </ItemGroup>

  <ItemGroup>
    <None Update="Scripts\install.bat">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="Scripts\uninstall.bat">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

什么鬼?咋是<ApplicationManifest>\app.manifest</ApplicationManifest>, 原来是VS2017的BUG, OK,手动修改成<ApplicationManifest>app.manifest</ApplicationManifest>,搞定!

ABOUT

I'm a developer, I use C/C++, Java, C# and Swift, but I also embrace all the new stuff.

I'm working at Tencent. My family live in Hangzhou, Zhejiang, China. Maybe the difference with other programmers is I already married, and have a lovely daughter. (^<>^)

A man like me, is unique in the world of existence, no matter where you go, there belonging to my stage. Like desert gold, light can not hide forever! Especially my messy hair, melancholy eyes, sigh of stubble, handsome face, are deeply addicted whom even I.

ELSEWHERE