5

I'm using a WriteLinesToFile to update a change log file (txt). It appends the text to the end of the file. Ideally, I'd like to be able to write the changes to the start of this file.

Is there a simple task (e.g. in the Community or Extension packs) that does this?

dommer
  • 19,610
  • 14
  • 75
  • 137
  • Similar to https://stackoverflow.com/questions/21491914/how-can-i-insert-lines-into-a-file-in-an-msbuild-task/21500030#21500030 which also has a good answer. – Jack Miller Jun 06 '18 at 09:00

1 Answers1

14

I haven't seen something like that in the custom task pack.

You could cheat by using ReadLinesFromFile and WriteLinesToFile :

<PropertyGroup>
  <LogFile>log.txt</LogFile>
</PropertyGroup>

<ItemGroup>
  <Log Include="Line1"/>
  <Log Include="Line2"/>
</ItemGroup>

<Target Name="WriteFromStart">
  <ReadLinesFromFile File="$(LogFile)" Condition="Exists('$(LogFile)')">
    <Output TaskParameter="Lines" ItemName="Log"/>
  </ReadLinesFromFile>

  <WriteLinesToFile File="$(LogFile)" 
                    Lines="@(Log)" 
                    Condition="@(Log) != '' And (@(Log) != '\r\n' Or @(Log) != '\n')"
                    Overwrite="true">
  </WriteLinesToFile>
</Target>

Or you could create a custom task.

weir
  • 4,521
  • 2
  • 29
  • 42
Julien Hoarau
  • 48,964
  • 20
  • 128
  • 117
  • Is there any way to stop it stripping the blank lines (between log entries)? – dommer Sep 03 '10 at 15:17
  • 2
    Add a condition to WriteLinesToFile --> Condition="@(Log) != '' And (@(Log) != '\r\n' Or @(Log) != '\n')" – Julien Hoarau Sep 03 '10 at 15:39
  • I bit the bullet yesterday and wrote a custom task, but I might go back to this as I don't like maintaining stuff unless it absolutely necessary. Thanks. – dommer Sep 04 '10 at 20:01
  • @dommer: If you're doing a good bit of exotic stuff in this direction, I'd suggest considering a powershell inline task or psake – Ruben Bartelink Sep 09 '10 at 21:31