How to copy and rename file to output folder as part of build

Viewed 3341

I believe this is more of an msbuild-related question. Have a .net core app and I need to conditionally publish a file and based on the build config selected in Visual Studio 2019, the file should be renamed before publishing to the target.

So Im looking at modifying the csproj file (which is nothing but an msbuild file itself) I dont see a condition option on the copy task https://docs.microsoft.com/en-us/visualstudio/msbuild/copy-task?view=vs-2019

The goal Im after, is if I have 3 different files
tester-notes.dev.json tester-notes.debug.json tester-notes.prod.json

If prod is selected as a build config, I want the file published to be tester-notes.prod.json, but renamed to tester-notes.json

1 Answers

Assuming you have three files(build action = None) in Solution Explorer when developing:

enter image description here

You can use something similar to this script to rename and copy to publish folder if you're using FileSystem publish mode:

<ItemGroup Condition="$(Configuration)=='Dev'">
    <FileToRename Include="$(ProjectDir)\tester-notes.dev.json" />
  </ItemGroup>
  <ItemGroup Condition="$(Configuration)=='Debug'">
    <FileToRename Include="$(ProjectDir)\tester-notes.debug.json" />
  </ItemGroup>
  <ItemGroup Condition="$(Configuration)=='Prof'">
    <FileToRename Include="$(ProjectDir)\tester-notes.prof.json" />
  </ItemGroup>

  <Target Name="DoSthAfterPublish1" AfterTargets="Publish" Condition="$(Configuration)=='Dev'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.dev.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

  <Target Name="DoSthAfterPublish2" AfterTargets="Publish" Condition="$(Configuration)=='Debug'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.debug.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

  <Target Name="DoSthAfterPublish3" AfterTargets="Publish" Condition="$(Configuration)=='Prof'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.prof.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

And if you can reset tester-notes.debug.json to tester-notes.Debug.json,, then we may combine the three targets into one by using DestinationFiles="@(FileToRename->Replace('.$(Configuration).json','.json'))". Hope it makes some help :)

In addition:

According to the Intellisense we can find the Copy task supports Condition:

enter image description here

Related