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

.NET-Core: Running the built application in PostBuildEvent

我有一个 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 效果不佳。

有办法吗?

最简单的方法是重新使用已经计算命令的内置目标。 dotnet run 也会构建项目,因此调用 dotnet run 可能会导致无限递归 - 而应该是 dotnet path/to/the.dll。此外,PostBuildEvent 被认为已弃用,并且在添加 post 构建命令时具有 problems in SDK-based projects (an upcoming 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="..." 属性,它们将被传递到应用程序(不需要 --)。

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

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