crayden
crayden

Reputation: 2270

How to store an environment variable in a .NET Core console application?

Following the example found here, the code requires setting an environment variable in the command line before running.

setx storageconnectionstring "<yourconnectionstring>"

Is it possible to store this variable somewhere inside of a .NET Core console application? How would it be accessed by the code if this is possible?

Upvotes: 1

Views: 4832

Answers (1)

UNOPARATOR
UNOPARATOR

Reputation: 706

You can set the environment via command prompt (cmd), powershell using this syntax:

setx variable_name "value_to_store_as_a_string"

or by using the System Properties (right click This PC, select Properties, then click Advanced system settings) window and clicking the Environment Variables... button (you can see all user & system environments and create, edit or delete them). These will be persisted between restarts.

Or back to your question, you can use a config file such as app.config (which is an XML file) or appsettings.json (which is a JSON file). There are several ways to access it. Here is a sample appsettings.json file:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "SQL": "Data Source=servername;Initial Catalog=databasename;User Id=myuser;Password=complexpassword;",
    "MongoDb": "mongodb://username:[email protected]:27017,10.0.0.3:27017,10.0.0.3:27017,10.0.00.4:27017/?replicaSet=myreplicaset"
  },
  "variable_name": "string_value",
  "boolean_variable_name": false,
  "integer_variable_name": 30
}
var appSettings = ConfigurationManager.AppSettings;

string myVariable = appSettings["variable_name"];
public static IConfigurationRoot Configuration;

static void Main(string[] args)
{
    var configBuilder = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    Configuration = configBuilder.Build();
    
    string myVariable = hostContext.Configuration.GetValue<string>("variable_name");
}
static void Main(string[] args)
{
    new HostBuilder()
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.SetBasePath(basePath: Directory.GetCurrentDirectory());
        config.AddJsonFile("appsettings.json", optional: true);
        config.AddEnvironmentVariables();
    })
    .ConfigureServices((hostContext, services) =>
    {
        string myVariable = hostContext.Configuration.GetValue<string>("variable_name");
    })
    .RunConsoleAsync().Wait();
}

You can read another post here.

You can read more at MS documentation from here.

Upvotes: 3

Related Questions