Mister Dev
Mister Dev

Reputation: 10431

How do I get and set Environment variables in C#?

How can I get Environnment variables and if something is missing, set the value?

Upvotes: 275

Views: 366564

Answers (10)

Lou
Lou

Reputation: 403

While there are many good examples on this page, sometimes we need real world examples to see the actual process at work. Here's what I use to store data in an environment variable while the user is logged into their computer:

using System;
using System.Windows.Forms;

namespace Environment_Variables
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string Claim_Type;  // CL104 is Physician, HO170 is Hospital
            bool toDelete = false;

            // Check whether the environment variable exists.
            // If stored as Process, it will be deleted after the process ends.
            // If stored as User, it will be deleted after the user logs out of the machine.
            // If stored as Machine, it will be deleted after the machine is restarted.
            Claim_Type = Environment.GetEnvironmentVariable("Phys_Hosp", EnvironmentVariableTarget.User);

            // If necessary, create it.
            if (Claim_Type == null)
            {
                Environment.SetEnvironmentVariable("Phys_Hosp", "CL104", EnvironmentVariableTarget.User);
                toDelete = true;

                // Now, retrieve the value.
                Claim_Type = Environment.GetEnvironmentVariable("Phys_Hosp", EnvironmentVariableTarget.User);

                // Display the new value.
                MessageBox.Show("New value for Claim Type: " + Claim_Type);
            }
            else 
            {
                // Display the existing value being stored in the target.
                MessageBox.Show("Existing value for Claim Type: " + Claim_Type);
            }
        }
    }
}

Upvotes: 0

OfirD
OfirD

Reputation: 10461

Environment variables can also be placed in an application's app.config or web.config file, by their name bounded with percentages (%), and then expanded in code.

  • Note that when a value of an environment variable is changed (or a new one is set), Visual Studio should be closed and reopened.

For example, in app.config:

<connectionStrings>
    <add name="myConnectionString" connectionString="%DEV_SQL_SERVER_CONNECTION_STRING%" providerName="System.Data.SqlClient" />
</connectionStrings>

And then in the code:

string connectionStringEnv = ConfigurationManager.AppSettings["myConnectionString"];
string connectionString = System.Environment.ExpandEnvironmentVariables(connectionStringEnv); 

Upvotes: 4

D. Kermott
D. Kermott

Reputation: 1663

In Visual Studio 2019 -- Right Click on your project, select Properties > Settings, Add a new variable by giving it a name (like ConnectionString), type, and value. Then in your code read it so:

var sConnectionStr = Properties.Settings.Default.ConnectionString;

These variables will be stored in a config file (web.config or app.config) depending upon your type of project. Here's an example of what it would look like:

  <applicationSettings>
    <Testing.Properties.Settings>
      <setting name="ConnectionString" serializeAs="String">
        <value>data source=blah-blah;etc-etc</value>
      </setting>
    </Testing.Properties.Settings>
  </applicationSettings>

Upvotes: 0

Vijendran Selvarajah
Vijendran Selvarajah

Reputation: 1350

If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.

var builder = new ConfigurationBuilder()
                .AddJsonFile("appSettings.json")
                .AddEnvironmentVariables(prefix: "ABC_")

var config = builder.Build();

enter image description here

According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_") line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.

Upvotes: 2

Tom Stickel
Tom Stickel

Reputation: 20391

Get and Set

Get

string getEnv = Environment.GetEnvironmentVariable("envVar");

Set

string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);

Upvotes: 49

Patrick Desjardins
Patrick Desjardins

Reputation: 140753

Use the System.Environment class.

The methods

var value = System.Environment.GetEnvironmentVariable(variable [, Target])

and

System.Environment.SetEnvironmentVariable(variable, value [, Target])

will do the job for you.

The optional parameter Target is an enum of type EnvironmentVariableTarget and it can be one of: Machine, Process, or User. If you omit it, the default target is the current process.

Upvotes: 364

SpeedyNinja
SpeedyNinja

Reputation: 411

This will work for an environment variable that is machine setting. For Users, just change to User instead.

String EnvironmentPath = System.Environment
                .GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);

Upvotes: 22

Ajit
Ajit

Reputation: 11

I could be able to update the environment variable by using the following

string EnvPath = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) ?? string.Empty;
if (!string.IsNullOrEmpty(EnvPath) && !EnvPath .EndsWith(";"))
    EnvPath = EnvPath + ';';
EnvPath = EnvPath + @"C:\Test";
Environment.SetEnvironmentVariable("PATH", EnvPath , EnvironmentVariableTarget.Machine);

Upvotes: 0

Karthik Chintala
Karthik Chintala

Reputation: 5545

Environment.SetEnvironmentVariable("Variable name", value, EnvironmentVariableTarget.User);

Upvotes: 9

Nathan Bedford
Nathan Bedford

Reputation: 9214

I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.

I didn't want that to happen...that means folders in the path such as '%SystemRoot%\system32' were being re-written as 'C:\Windows\system32'. To get the un-expanded path, I had to use this:

string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

Worked like a charm for me.

Upvotes: 41

Related Questions