August 17, 2020

Run a target action before or after publishing

Target tag allow us to execute custom actions on particular events. We can also specify the order of target actions in a particular sequence we need. We have different target attributes for publish profiles, but in this post I will demonstrate BeforeTargets and AfterTargets for publish event.

Microsoft Docs:

BeforeTargets and AfterTargets. These Target attributes specify that this target should run before or after the specified targets (MSBuild 4.0).

We can use these built-in BeforePublish and AfterPublish targets to execute an action before or after the publish. For exmaple, following tag logs the console messages before and after publishing.

<Target Name="MyCustomActionBeforePublish" BeforeTargets="BeforePublish">
    <Message Text="Logging Message BeforePublish" Importance="high" />
  </Target>
  <Target Name="MyCustomActionAfterPublish" AfterTargets="AfterPublish">
    <Message Text="Logging Message AfterPublish" Importance="high" />
</Target>

Just logging a console message is not very helpful. You can perform a variety of options, one could be to copy files from a particular source directory. Following example allows the publishing profile to copy files from the path specified in Include attribute of MySourceFiles to the destination path specified in DestinationFolder attribute of Copy tag. Since we are using the event name AfterPublish, the source content will be copied after it completes the publishing.

<Target Name="MyCustomActionAfterPublish" AfterTargets="AfterPublish">
    <ItemGroup>
      <MySourceFiles Include="C:\Test\ExternalContent\*.*"/>
    </ItemGroup>
    <Copy SourceFiles="@(MySourceFiles)" DestinationFolder="bin\Debug\netcoreapp2.2\publish\TestTarget\"/>
  </Target>

In this exmaple, we are using absolute path in MySourceFiles tag, you can also use relative path as illustrated in DestinationFolder attribute of Copy tag.

References:

No comments:

Post a Comment