codymanix
codymanix

Reputation: 29468

How to integrate conditional logic in postbuild events

Hi I have a visual studio project which includes postbuildevents in the following form:

MyTool.exe $(ProjectDir)somesrcfile.txt $(TargetDir)sometargetfile.bin

Now I want to add some logic saying that these steps are taking place only if the files have changed. In peudocode:

if (somesrcfile.txt is newer than sometargetfile.bin) { MyTool.exe $(ProjectDir)somesrcfile.txt $(TargetDir)sometargetfile.bin }

Can I do this with MsBuild?

EDIT: I just tried it with a simple copy command but it seems not to work. Also the message is not displayed when I build the solution.

<ItemGroup>
    <MyTextFile Include="*.txt" />
  </ItemGroup>

  <Target Name="Build" Inputs="@(MyTextFile)" Outputs="@(MyTextFile->'%(Filename).bin')">
      <CustomBuild>
        <Message>Encoding files...</Message>
        <Command>
            copy %(Identity) %(Filename).bin
        </Command>
        <Outputs>$(OutDir)%(Identity)</Outputs>
      </CustomBuild>
  </Target>

Upvotes: 1

Views: 1399

Answers (1)

Eric Eijkelenboom
Eric Eijkelenboom

Reputation: 7021

Yes, it is possible by using the Inputs and Outputs attributes on your target.

See: How to: Build incrementally

In your case, it would look something like this:

  <Target Name="AfterBuild" DependsOnTargets="Test">
  </Target>

  <ItemGroup>
    <MyTextFile Include="*.txt" />
  </ItemGroup>

  <Target Name="Test" Inputs="@(MyTextFile)" Outputs="@(MyTextFile->'%(FileName).bin')">
    <Message Text="Copying @(MyTextFile)" Importance="high"/>

    <Copy SourceFiles="@(MyTextFile)"  DestinationFiles="@(MyTextFile->'%(FileName).bin')" />

  </Target>

This target will only run if input files are newer than output files.

Upvotes: 4

Related Questions