.NET-Core:在PostBuildEvent中运行构建的应用程序

时间:2017-06-21 17:33:42

标签: msbuild .net-core csproj

我有一个Exe项目,我希望在PostBuildEvent块中运行。我试过添加一个命令来做这几种方法,但似乎没什么用。

dotnet run -- -i
dotnet run TestConsole.csproj -- -i
dotnet run ../../../TestConsole.csproj -- -i
../../../init.bat (which contains a cd to the project directory and "dotnet run...")

前两个无法找到任何可以运行的东西。最后两个失败了。显然,dotnet build递归调用dotnet run并不能很好地工作。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

最简单的方法是重新使用已经计算命令的内置目标。 dotnet run也构建项目,因此调用dotnet run可能会导致无限递归 - 而应该是dotnet path/to/the.dll。此外,PostBuildEvent被视为已弃用,并且在添加帖子构建命令时具有problems in SDK-based projectsupcoming VS update will add targets instead。)

要在构建时执行程序,可以将以下内容添加到csproj文件中:

<Project Sdk="Microsoft.NET.Sdk">

  <!-- other project content -->

  <Target Name="RunAfterBuild" AfterTargets="Build">
    <Exec Command="$(RunCommand) $(RunArguments)" WorkingDirectory="$(RunWorkingDirectory)" />
  </Target>
</Project>

AfterTargets="Build"将导致在构建之后运行,即使它是通过VS调用的。如果在VS中处理项目时不应该运行它,则可以添加

Condition=" '$(BuildingInsideVisualStudio)' != 'true' "

作为<Target>元素的属性。

$(RunCommand)$(RunArguments)$(RunWorkingDirectory) are defaulted by the SDK的值,并包含涉及主机/ exe文件等的正确路径。您可以将任何自定义参数添加到Command="..."属性,它们将传递给应用程序(不需要--)。

为了添加在通过dotnet运行构建/运行项目时也会受到尊重的全局参数,可以设置项目中的StartArguments属性。它将自动添加到RunArguments

<Project …>
  <PropertyGroup>
    <StartArguments>--sample-option</StartArguments>
  </PropertyGroup>
  <!-- other content -->
</Project>