Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSBuild copy or create file if not exists

I have a simple requirement to create a file in the project directory called user.config, but only if it doesn't exist already.

First attempt:

  <Target Name="BeforeBuild">
    <ItemGroup>
      <Line Include="line01"><Text>&lt;appSettings&gt;&lt;/appSettings&gt;</Text></Line>
      <LineText Include="%(Line.Text)" />
    </ItemGroup>
    <WriteLinesToFile File="user.config" Lines="@(LineText)" Overwrite="false" />
  </Target>

Doesn't work because it appends to file

Second attempt:

  <Target Name="BeforeBuild">
    <CreateItem Include="user_example.config">
      <Output ItemName="ItemsThatNeedToBeCopied" TaskParameter="Include" />
    </CreateItem>
    <Copy SourceFiles="@(ItemsThatNeedToBeCopied)" DestinationFolder="$(ProjectDir)" Condition="!Exists('%(RootDir)%(Directory)%(Filename)%(Extension)')" />
  </Target>

Doesn't work because nothing seems to happen and there is nothing in the verbose msbuild output telling me anything about why

Any MSBuild expert should easily see what I'm doing wrong...

like image 853
Trygve Avatar asked Mar 17 '17 10:03

Trygve


1 Answers

The first attempt is pretty much the canonical way to do this and you basically got it right except for the missing condition (which every MsBuild task supports):

<WriteLinesToFile File="user.config" Lines="@(LineText)" Overwrite="True"
                  Condition="!Exists('user.config')"/>
like image 67
stijn Avatar answered Oct 24 '22 18:10

stijn