Is there an `appsettings.json` configuration file at the machine level and user levels?

Viewed 313

I know that, for a desktop application, the old *.config mechanism had four levels of configuration files:

  • machine.config - in the .net install directory
  • app.config - in the application's directory
  • user.config - in the user's roaming directory
  • user.config - in the user's local directory

What is the equivalence of those files in the new system, the one that uses JSON files?

1 Answers

You can do all this granularly with the ConfigurationBuilder, it has the flexibility to do all those concerns and more by just adding the known configuration files in the right order. The downside is it's a little more verbose. However, write yourself an extension method if you want:

Note : If you are using asp.netcore you get access to the IConfigurationRoot in the configuration methods E.g ConfigureAppConfiguration, ergo you don't need to instantiate a new ConfigurationBuilder as shown below.

var configuration = new ConfigurationBuilder()
   .SetBasePath(...)
   // some machine config
   .AddJsonFile(@"<The path to your globalSettings>\appsettings.json", optional: true) 
   // Your main app settings
   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
   // environment specific
   .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
   // Machine specific
   .AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true)
    // user specific
   .AddJsonFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Your App Name","appsettings.json"), optional: true)
   .AddEnvironmentVariables()
   ...

Disclaimer : The following is not meant to be the greatest code in the world, it's just a tribute. You will need to do whatever it is that makes sense to you and your environment.

The longer story:

The IConfigurationRoot is just a collection of providers and sources. The providers collapse to a collection of key value pairs. Each subsequent provider you add has the ability to override the previous providers values if available, and roughly 1000 times better than the old app.config/web.config paradigm.

Related