IlirB
IlirB

Reputation: 1430

MSBuild WriteLinesToFile without new line at the end

I want to write a number in a text file using WriteLinesToFile but the task is putting a line feed at the end which causes me trouble when i want to read or combine in other places

Example:

<WriteLinesToFile File="$(TextFile)" Lines="@(BuildNumber)" Overwrite="true"/>

UPDATE as the user comment below:

The problem that I had was that I was using a very simple command in Property to read the content of a file $([System.IO.File]::ReadAllText("$(TextFile)")) and I really want to use this one but it also included the line feed from WriteLinesToFiles. I ended up using similar solution like yours using ReadLinesFromFile.

Upvotes: 4

Views: 4304

Answers (1)

ka05
ka05

Reputation: 664

There is a slight dissconnect between the title and the description. I would have liked to post this "answer" as an edit, but do not have enough reputation points :) Do you have a problem with the newline at the end of a file, or do you have a problem ignoring that newline? Could you please clarify?

One way how I suppose you could ignore that newline follows.

This small snippet of code writes a build number to a file, then reads it out and then increments the number read by 1.

<Target Name="Messing_around">
  <PropertyGroup>
      <StartBuildNumber>1</StartBuildNumber>
  </PropertyGroup>
  <ItemGroup>
      <AlsoStartBuildNumber Include="1"/>
  </ItemGroup>
  <!-- Use a property 
  <WriteLinesToFile File="$(ProjectDir)test.txt" Lines="$(StartBuildNumber)" Overwrite="true"/>      
  -->
  <WriteLinesToFile File="$(ProjectDir)test.txt" Lines="@(AlsoStartBuildNumber)" Overwrite="true"/>
  <ReadLinesFromFile File="$(ProjectDir)test.txt">
      <Output
          TaskParameter="Lines"
          ItemName="BuildNumberInFile"/>
  </ReadLinesFromFile>
  <PropertyGroup>
    <OldBuildNumber>@(BuildNumberInFile)</OldBuildNumber>
    <NewBuildNumber>$([MSBuild]::Add($(OldBuildNumber), 1))</NewBuildNumber>
  </PropertyGroup>
  <Message Importance="high" Text="Stored build number: @(BuildNumberInFile)"/>
  <Message Importance="high" Text="New build number: $(NewBuildNumber)"/>
</Target>

And this is what I see

Output:
1>Build started xx/xx/xxxx xx:xx:xx.
1>Messing_around:
1>  Stored build number: 1
1>  New build number: 2
1>
1>Build succeeded.

If you attempting to read, in an MSBuild Task, a single line containing only a number from a file with a trailing line feed, then you should not have a problem.

As a side note: With the little information at hand I'd assume that BuildNumber is an Item in an ItemGroup. If you have only one build number to deal with, perhaps Property may have been an option. But then, again, I haven't been tinkering with MSBuild for too long. So, I am open to feedback on the Item vs Property issue.

Upvotes: 3

Related Questions