Question

I have a numer, "n" in a property in MSBuild. I also have a string "Str" that needs to be duplicated n-times to achieve a final string that is the repetition of "Str" n times.

Eg. If n is 3 and Str is "abc", what I want to obtain is "abcabcabc"

Since one cannot loop in MSBuild, I don't know how to achieve this. Perhaps with an item group, but how do I create one based on a property containing an "n" count?

Thanks!

Was it helpful?

Solution

usually for things like this I resolve to using inline C#, as it costs me less time than searching all over the internet to find a 'true' msbuild solution; here you go:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <PropertyGroup>
    <MyString>abc</MyString>
    <Count>3</Count>
  </PropertyGroup>

  <UsingTask TaskName="RepeatString" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
      <s ParameterType="System.String" Required="true" />
      <n ParameterType="System.Int32" Required="true" />
      <result ParameterType="System.String" Output="true" />
    </ParameterGroup>
    <Task>
      <Code Type="Fragment" Language="cs"><![CDATA[
        result = string.Concat( Enumerable.Repeat( s, n ) );
        ]]></Code>
    </Task>
  </UsingTask>

  <Target Name="doit">
    <RepeatString s="$(MyString)" n="$(Count)">
      <Output PropertyName="result" TaskParameter="result" />
    </RepeatString>
    <Message Text="Result = $(result)"/>
  </Target>

</Project>

OTHER TIPS

To create a String repeated n times, you can also do this (at least in MSBuild Tools v4.0):

<SomeRepeatedString>$([System.String]::New("-", 40))</SomeRepeatedString>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top