问题
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><appSettings></appSettings></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