- 1 year ago
Prefixed Environment Variables in .NET 6
In .NET 6, you can use the ConfigurationBuilder
class from the Microsoft.Extensions.Configuration
namespace to read prefixed environment variables. The ConfigurationBuilder
allows you to build a configuration object by specifying various configuration sources, including environment variables.
Here's an example of how you can read prefixed environment variables in .NET 6:
csharpusing Microsoft.Extensions.Configuration;
using System;
class Program
{
static void Main(string[] args)
{
// Create a new configuration builder
var configBuilder = new ConfigurationBuilder();
// Add the environment variables as a configuration source
configBuilder.AddEnvironmentVariables();
// Build the configuration
var config = configBuilder.Build();
// Read prefixed environment variables
var myVariable1 = config["MyPrefix_MyVariable1"];
var myVariable2 = config["MyPrefix_MyVariable2"];
// Print the values
Console.WriteLine($"MyVariable1: {myVariable1}");
Console.WriteLine($"MyVariable2: {myVariable2}");
}
}
In this example, the ConfigurationBuilder
is used to build a configuration object. The AddEnvironmentVariables
method is called to add the environment variables as a configuration source. By default, it reads all environment variables and treats them as configuration values.
To access the prefixed environment variables, you can use the configuration object and specify the prefixed key, such as "MyPrefix_MyVariable1"
and "MyPrefix_MyVariable2"
. The config
object allows you to retrieve the values of the prefixed environment variables.
Make sure to replace "MyPrefix"
with your actual prefix in the code.
Compile and run the application, and it will read the prefixed environment variables and print their values.
Note: The ConfigurationBuilder
can be used in various .NET application types, such as console apps, web apps, or ASP.NET Core apps. Adjust the code according to your application type and requirements.