MSBuild copy or create file if not exists

我只是一个虾纸丫 提交于 2020-08-07 07:27:04

问题


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...


回答1:


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')"/>


来源:https://stackoverflow.com/questions/42854860/msbuild-copy-or-create-file-if-not-exists

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