Need a "post clean event" in Visual Studio

Hat tip to @scrat789 regarding AfterTargets.

For VS 2017, v15.6.0 Preview 2.0, I ended up with the following:

  <Target Name="MyDistClean" AfterTargets="Clean">
    <Message Text="Deleting wwwroot\dist files" Importance="high" />
    <Delete Files="$(ProjectDir)\wwwroot\dist\*.*" ContinueOnError="true" />
  </Target>

A few things:

  • Notice I'm using a unique target name, MyDistClean. Specifying the name, AfterClean, did not work.
  • It wasn't necessary to reload the csproj after editing in order to run/test the Clean task.
  • Message importance is set high to avoid changing the MSBuild verbosity level mentioned here at SO: AfterClean Target Doesn't Get Invoked When I Clean The Project
  • MyDistClean task was processed at both the solution and project scope.

Here's the task improved to obliterate the webpack dist directory upon Clean:

  <Target Name="MyDistClean" AfterTargets="Clean">
    <ItemGroup>
      <DistDir Include="$(ProjectDir)wwwroot\dist" />
    </ItemGroup>
    <Message Text="Deleting @(DistDir)" Importance="high" />
    <RemoveDir Directories="@(DistDir)" />
  </Target>

You can edit the project file directly and add the target to the end of the file. BeforeClean and AfterClean are targets as explained here:

https://docs.microsoft.com/en-us/visualstudio/msbuild/how-to-extend-the-visual-studio-build-process?view=vs-2019

You should be able to put a Delete task in the target.

EDIT Just tested this (right-click project -> unload -> right click -> edit) and the following target is what you need:

<Target Name="AfterClean">
    <Delete Files="$(TargetDir)\*.txt" />
</Target>

This works when you clean the project but not the solution - it works but not 100%.