照著 MSDN Create and Embed an Application Manifest (UAC) 一文的說明,為.NET程式附加.manifest檔案註記為需管理者權限執行,並在Visual Studio專案屬性的Post Build Event中加入mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1",以便將manifest直接內嵌在EXE檔裡面。但編譯時一直彈出:

mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"" exited with code 9009.

爬文後,發現有兩種解法: 第一種是加上mt.exe的路徑(參考),但開發機器環境各異,寫死路徑可能會導致.csproj在另一台機器上編譯失敗。我決定使用第二種做法,用Notepad等文字編輯器開啟.csproj檔案,會看到如下內容:
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <PropertyGroup>
    <PostBuildEvent>mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"</PostBuildEvent>
  </PropertyGroup>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

將最後<Target ...>外圍的<!-- -->移除,再將<PropertyGroup><PostBuildEvent ...></PropertyGroup>搬到<Target Name="AfterBuild">之間,經過測試,果然就能順利編譯囉!

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
      <PropertyGroup>
        <PostBuildEvent>mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"</PostBuildEvent>
      </PropertyGroup>
  </Target>
</Project>

[2010-08-31更新] 感謝BillChung提醒,VS2008/VS2010已會自動將manifest需要管理權限的註記編譯入EXE檔案,故已不需要mt.exe嵌入的程序。特此補充!


Comments

Be the first to post a comment

Post a comment