Search code examples
msbuild

MSbuild : read files with line feeds


Using MSBuild, how to read a text file with carriage return/line feed and get each line content in a property? The file goes like

Prod;2.13
Pre-Prod;2.14
Test;2.15

And I would like to get

<PropertyGroup>
    <_ProdVersion>2.13</_ProdVersion>
    <_PreProdVersion>2.14</_PreProdVersion>
    <_TestVersion>2.15</_TestVersion>
</PropertyGroup>

So far, i got this but it don't get where i can implement that line-feed splitting step and MSBuild Online Documentation is pretty light:

<ReadLinesFromFile Condition="'$(Configuration)' == 'Debug'" File="$(MSBuildThisFileDirectory)/Resources/Others/MyFiles.txt">
    <Output TaskParameter="Lines" ItemName="MyItem" />
</ReadLinesFromFile>
<ItemGroup>
    <Lines Include="@(MyItem)">
        <Line_test>$([System.String]::Copy('%(MyItem.Identity)'))</Line_test>
    </Lines>
</ItemGroup>
<PropertyGroup>
    <_test>%(Lines.Line_test)</_test>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">           
    <_TestLine1>$(_test.Split(';')[0])</_TestLine1>
    <_TestLine2>$(_test.Split(';')[1])</_TestLine2>         
</PropertyGroup>

Solution

  • You can read the contents of a text file directly into properties like this Raymond Chen article shows:

      <PropertyGroup>
        <FileContent>$([System.IO.File]::ReadAllText('$(ProjectDir)..\version.txt').Trim())</FileContent>
        <LibTidyVersion>$([System.Text.RegularExpressions.Regex]::Split($(FileContent), '\r?\n')[0].Trim())</LibTidyVersion>
        <ReleaseDate>$([System.Text.RegularExpressions.Regex]::Split($(FileContent), '\r?\n')[1].Trim())</ReleaseDate>
      </PropertyGroup>
    

    The FileContent property contains the full text content of the input file. The other properties split FileContent into lines and then take first or second line respectively.

    It's not as dynamic as it requires the properties' values to be on specific lines, but it is a quick and easy solution and has the advantage of being evaluated very early in the build process.