Peter
Peter

Reputation: 11

How to run custom MSBuild target if files changed

I want to achieve the following msbuild behaviour:

  1. I run build on clear project and my custom target "OnFilesChange" fired.
  2. I do not change anything and run build again, my custom target "OnFilesChange" is not fired and the whole build process skipped (nothing changed).
  3. I change only tracked file from ./Plugins folder, only my custom target "OnFilesChange" fired, but not the whole build process.

Is it possible to do?

I have empty c# project with following structure:

enter image description here

The .csproj file contains following:

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

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <SourceFilesFiles Include="Plugins\test.txt" />
    <DestinationFiles Include="$(OutputPath)\Plugins\test.txt" />
  </ItemGroup>

  <Target Name="OnFilesChange" Inputs="@(SourceFilesFiles)" Outputs="@(DestinationFiles)">
    <Copy SourceFiles="@(SourceFilesFiles)" DestinationFiles="@(DestinationFiles)" />
  </Target>

</Project>

Here I tried to create a target (OnFilesChange) that on build should compare current ./Plugins/test.txt file with output ./bin/Debug/net8.0/Plugins/test.txt file. And if it was changed run my target "OnFilesChange". I tried it to save incremental build flow with all MSbuild optimisations but it is does not work properly.

P.S.

I did not find nice solution for this problem, but I found pretty nice workaround for this problem. Just include this in your .csproj file:

  <ItemGroup>
    <AdditionalFiles Include="path\to\you\files\**\*.*" Exclude="**\dist\**\*.*;**\node_modules\**\*.*;etc\files\to\exclude.txt" />
  </ItemGroup>

This workaround allows to track additional files and trigger normal build (instead of up-to-date).

Note: it is important that AdditionalFiles usually used for analyzers: https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Using%20Additional%20Files.md

Upvotes: 0

Views: 58

Answers (0)

Related Questions