Build a string in MSBuild as a concatenation of a base string n-times

て烟熏妆下的殇ゞ 提交于 2019-12-12 18:05:53

问题


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!


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/13156540/build-a-string-in-msbuild-as-a-concatenation-of-a-base-string-n-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!