Programmatically accessing configuration settings allows your application to retrieve values at runtime, enabling dynamic behavior based on external configurations. This is particularly important for scenarios like deployment, multi-environment setups, and modifying application settings without modifying the source code.
In C# and the .NET ecosystem, configuration values can be accessed through various mechanisms, depending on whether you are working in a .NET Framework or .NET Core/.NET 5+ application.
In .NET Framework (such as WinForms, WPF, or Console applications), configuration data is commonly stored in XML configuration files like app.config or web.config, and you can access these settings programmatically through the ConfigurationManager class.
app.config:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="AppTitle" value="My Application" />
<add key="MaxUsers" value="100" />
</appSettings>
<connectionStrings>
<add name="DatabaseConnection"
connectionString="Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;" />
</connectionStrings>
</configuration>
ConfigurationManager:To read the values from the app.config file in .NET Framework, you use the ConfigurationManager class from the System.Configuration namespace.
using System;
using System.Configuration;
class Program
{
static void Main()
{
// Accessing appSettings
string appTitle = ConfigurationManager.AppSettings["AppTitle"];
Console.WriteLine("App Title: " + appTitle);
// Accessing connectionStrings
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
Console.WriteLine("Database Connection String: " + connectionString);
}
}
ConfigurationManager.AppSettings["KeyName"].ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString.In .NET Core and .NET 5+, configuration management is more flexible and is built around the IConfiguration interface. Configuration can be loaded from multiple sources, such as JSON files (appsettings.json), environment variables, command-line arguments, and more.
appsettings.json:{
"AppSettings": {
"AppTitle": "My Application",
"MaxUsers": 100
},
"ConnectionStrings": {
"DatabaseConnection": "Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
IConfiguration in .NET Core / .NET 5+:In .NET Core and .NET 5+, you need to use the IConfiguration interface, which is typically injected into classes via Dependency Injection.
appsettings.json in the Program.cs or Startup.cs:using Microsoft.Extensions.Configuration;
public class Program
{
public static void Main(string[] args)
{
// Build the configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) // Sets the base path
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // Adds appsettings.json file
.Build();
// Access configuration settings
string appTitle = configuration["AppSettings:AppTitle"];
int maxUsers = int.Parse(configuration["AppSettings:MaxUsers"]);
string dbConnection = configuration.GetConnectionString("DatabaseConnection");
// Output the settings to the console
Console.WriteLine($"App Title: {appTitle}");
Console.WriteLine($"Max Users: {maxUsers}");
Console.WriteLine($"Database Connection: {dbConnection}");
}
}
You can also access nested configuration sections using a colon (:) to denote the hierarchy (e.g., AppSettings:AppTitle).
string appTitle = configuration["AppSettings:AppTitle"];
For more complex settings, you can use the GetSection() method to retrieve entire sections:
IConfigurationSection appSettingsSection = configuration.GetSection("AppSettings");
string appTitle = appSettingsSection["AppTitle"];
int maxUsers = int.Parse(appSettingsSection["MaxUsers"]);
You can also bind an entire section of the configuration to a strongly typed class, making it easier to work with settings in a more object-oriented way.
Define a class that matches the structure of your configuration:
public class AppSettings
{
public string AppTitle { get; set; }
public int MaxUsers { get; set; }
}
Then bind the AppSettings section of the configuration to this class:
IConfigurationSection appSettingsSection = configuration.GetSection("AppSettings");
AppSettings appSettings = appSettingsSection.Get<AppSettings>();
Console.WriteLine($"App Title: {appSettings.AppTitle}");
Console.WriteLine($"Max Users: {appSettings.MaxUsers}");
This approach automatically maps the configuration settings into an object that can be accessed in a strongly-typed manner.
Connection strings can be accessed using the GetConnectionString() method in .NET Core and .NET 5+:
string dbConnection = configuration.GetConnectionString("DatabaseConnection");
.NET Core and .NET 5+ allow you to have environment-specific configuration files. These files override settings in appsettings.json depending on the environment in which the application is running. The common pattern is to use files like:
appsettings.Development.jsonappsettings.Production.jsonappsettings.Staging.jsonThis is useful for managing different settings in different environments (e.g., Development, Staging, Production).
You can specify the environment by setting the ASPNETCORE_ENVIRONMENT environment variable.
set ASPNETCORE_ENVIRONMENT=Development
You can configure the ConfigurationBuilder to load the appropriate configuration file based on the environment.
public class Program
{
public static void Main(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.Build();
// Access configuration
string appTitle = configuration["AppSettings:AppTitle"];
Console.WriteLine($"App Title: {appTitle}");
}
}
In this case, the application will load appsettings.json by default, and if the environment is set to Development, it will override the settings with appsettings.Development.json.
In addition to JSON files, .NET Core and .NET 5+ support loading configuration from various sources, such as:
For example, to load configuration from environment variables:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var environment = context.HostingEnvironment.EnvironmentName;
config.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
ConfigurationManager class from XML-based app.config or web.config files.IConfiguration interface, which supports multiple sources like appsettings.json, environment variables, and command-line arguments.appsettings.Development.json and appsettings.Production.json to manage different configurations for different environments.By leveraging these mechanisms, you can manage your application's configuration in a way that is both flexible and maintainable, providing
Open this section to load past papers