12

I'm trying to concatenate a few files during my build but the way I tried strips out the tabs and spaces leaving the output unformatted.

<CreateItem Include="Scripts\ApplicationModule.d.ts; Scripts\AccountModule.d.ts; Scripts\FeedModule.d.ts;">
  <Output TaskParameter="Include" ItemName="ApplicationDefinitionFiles" />
</CreateItem>

<ReadLinesFromFile File="%(ApplicationDefinitionFiles.FullPath)">
  <Output TaskParameter="Lines" ItemName="ApplicationDefinitionLines" />
</ReadLinesFromFile>

<WriteLinesToFile File="Scripts\ApplicationDefinition.d.ts" Lines="@(ApplicationDefinitionLines)" Overwrite="true" />

What's the way to preserve formatting?

parliament
  • 21,544
  • 38
  • 148
  • 238

1 Answers1

13

This is what I ended up with when faced with the same problem:

<Target Name="ConcatenateScripts">
  <!-- List all the files you want to concatenate. -->
  <ItemGroup>
    <ConcatFiles Include="
        Scripts\ApplicationModule.d.ts; 
        Scripts\AccountModule.d.ts;
        Scripts\FeedModule.d.ts;"/>
  </ItemGroup>

  <!-- Read the contents of the files (preserving tabs/spaces). -->
  <ItemGroup>
    <FileContents Include="$([System.IO.File]::ReadAllText(%(ConcatFiles.Identity)))"/>
  </ItemGroup>

  <!-- Write the result to a single file. -->
  <WriteLinesToFile File="Scripts\ApplicationDefinition.d.ts" Lines="@(FileContents)" Overwrite="true" />
</Target>

<!-- Concatenate scripts on AfterBuild. -->
<Target Name="AfterBuild">
  <CallTarget Targets="ConcatenateScripts"/>
</Target>

This is a modified version of this blog post but using $([System.IO.File]::ReadAllText(...) instead of the ReadLinesFromFile task, as suggested in this answer.

Community
  • 1
  • 1
Anders Fjeldstad
  • 10,724
  • 2
  • 33
  • 50
  • VS2013 Premium V12.0..31101.00 Update 4. When file has heading tabs or spaces, the concatenated result doesn't. All lines start from the left edge with text. I'm using other elements than or , but isn't important. BTW, if I set build output to "Diagnostics" VS prints that ReadLinesFromFile is invoked within the target. – Leo Y May 04 '15 at 17:01
  • This worked perfectly. I'm on 2015 update 2. The only hard part was finding this post! :) – crthompson Apr 25 '16 at 20:56
  • THANK YOU! PS If you want to put some "white space" between the concatenated files, you can just tack in some extra stuff. Example: where %0a is a carriage return. – granadaCoder Sep 18 '18 at 13:44