Appsettings.json relation to Solution Configuration

EuroEager2008 171 Reputation points
2021-12-27T19:24:09.637+00:00

Have a WPF app (VS2022 .Net 6 and Prism 8)
Want an appsettings.debug.json or similar to override the appsettings.json without changing the launch profile (just by the Debug or Release (or more) configuration.
Anyone knows how to do?

Using something like the following to build the configuration, but that relies on changed DOTNET_ENVIRONMENT variable.

IConfigurationRoot configurationRoot = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true)
    .Build();
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,822 questions
Visual Studio Debugging
Visual Studio Debugging
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Debugging: The act or process of detecting, locating, and correcting logical or syntactical errors in a program or malfunctions in hardware. In hardware contexts, the term troubleshoot is the term more frequently used, especially if the problem is major.
986 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,401 Reputation points
    2021-12-28T00:35:22.23+00:00

    In general, the Environment.GetEnvironmentVariable is really designed for running on different servers, dev, staging, prod. WPF does not have a launchSettings.json file which does allow you to swap out to a different environment like with ASP.NET and set on the start app button in Visual Studio.

    You could try something like the following in the pre-build event where you set Configuration for Conditional compilation symbol in the Build tab of project properties.

    copy appSettings.$(Configuration).json appSettings.json

    Edit, see this code sample which targets connections strings but can be adapted for other settings.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. EuroEager2008 171 Reputation points
    2021-12-28T20:33:47.653+00:00

    Thanks
    Meanwhile I did it by #if DEBUG #else preprocessor directives
    As you mention conditional compilation I remember doing this some time ago (other project) and it worked ok.
    The last suggestion seems to work as well, but I don't like the approach (selection code in production output).

    I think it is a bit strange that VS2022 doesn't have something easier for this, I refuse to believe I am alone needing this.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.