Search code examples
msbuildmsbuild-task

How to extract multiple lines to variables in msbuild


I came across the following post MSBuild ReadLinesFromFile all text on one line

From this I haven't been able to figure out how to do the following.

What should I do if I want to ReadAllLines but want to store each line in a different variable without the semicolon?

<ReadLinesFromFile File="@(File)">
    <Output TaskParameter="Lines" ItemName="FileContents" />
</ReadLinesFromFile>
<Line1>"What should I do here?" </Line1>
<Line2>"What should I do here?" </Line2>

Solution

  • Read the content into a property, then split that property and get an item out of it. This of course requires that you know on beforehand that the file will have (at least) as many lines as you have properties.

    <Target Name="ReadFile">
      <ReadLinesFromFile File="$(MyInputFile)">
        <Output TaskParameter="Lines" PropertyName="FileContents"/>
      </ReadLinesFromFile>
    </Target>
    
    <Target Name="CreateProperties" DependsOnTargets="ReadFile">
      <PropertyGroup>
        <Line0>$([System.String]::Copy( $(FileContents) ).Split( ';' )[ 0 ])</Line0>
        <Line1>$([System.String]::Copy( $(FileContents) ).Split( ';' )[ 1 ])</Line1>
      </PropertyGroup>
    </Target>