Andrew Shepherd
Andrew Shepherd

Reputation: 45222

app.config file in the new .csproj format

Visual studio have provided a slimmed-down .csproj file format.

I am trying to build a .NET Framework app (version 4.6.1), but use the new hand-editable file.

Similar to the previous behavior, I want the app.config file copied to the output directory, but renamed to <output_exe>.config (where output_exe is the name of the executable file).

What do we put in the .csproj file for this to happen?

This does not work, because it doesn't rename the file:

<ItemGroup>
  <Content Include="App.config">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>

Upvotes: 9

Views: 8928

Answers (2)

Martin Ullrich
Martin Ullrich

Reputation: 100543

Just add the AppConfig property that msbuild and tooling expects for this feature:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net472</TargetFramework>
    <AppConfig>App.config</AppConfig>
  </PropertyGroup>

</Project>

This enables the PrepareForBuild msbuild target to automatically pick up the file and subsequent build steps can also edit this file as the logical file - e.g. the SDK will modify the startup/supportedRuntime section based on the TargetFramework that is defined. Adding this as a custom item or build step would loose this ability.

Upvotes: 23

LoLance
LoLance

Reputation: 28086

Try adding scripts like below to do that job:

  <ItemGroup>
    <Content Include="App.config">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

and

  <Target Name="MyCustomTarget" AfterTargets="build">
    <Move SourceFiles="$(OutputPath)\App.config" DestinationFiles="$(OutputPath)\$(AssemblyName).config" />
  </Target>

The first script can make sure the App.config file will be copied to output folder, and second script will rename the file with AssemblyName(name of executable file) after build target.

More details: If we need ProjectName.exe.config, then use $(OutputPath)\$(AssemblyName).exe.config. If we need ProjectName.config, then use $(OutputPath)\$(AssemblyName).config. We can customize the format of the renamed file according to what we need.

Upvotes: -1

Related Questions