How can I use BeforeBuild and AfterBuild targets with Visual Studio 2017?

.net, .net-core, csproj, msbuild, visual-studio-2017

Solution

The associated MSBuild git issue recommends not using BeforeBuild/AfterBuild as task names going forward, instead name the task appropriately and wiring up against targets

<Project Sdk="Microsoft.NET.Sdk"> 
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>

  <!-- Instead of BeforeBuild target -->
  <Target Name="MyCustomTask" BeforeTargets="CoreBuild" >
      <Message Text="Should run before build" Importance="High" />
  </Target>

  <!-- Replaces AfterBuild target -->
  <Target Name="AnotherCustomTarget" AfterTargets="CoreCompile">
      <Message Text="Should run after build" Importance="High" />
  </Target>    
</Project>

This gets you an idiomatic VS 2017 project file, but which targets you trigger before/after is still a matter of some debate at this time

Problem

After upgrading to a csproj to use Visual Studio 2017 and Microsoft.NET.Sdk, my "BeforeBuild" and "AfterBuild" targets are no longer running. My file looks like this: ``` <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net46</TargetFramework> </PropertyGroup> <!-- my targets that don't run --> <Target Name="BeforeBuild"> <Message Text="Should run before build" Importance="High" /> </Target> <Target Name="AfterBuild"> <Message Text="Should run after build" Importance="High" /> </Target> </Project> ```

Original source

Related problems