How can I get Environnment variables and if something is missing, set the value?
9 Answers
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.

- 25,467
- 18
- 120
- 187

- 136,852
- 88
- 292
- 341
-
44Also note the optional third parameter: System.Environment.SetEnvironmentVariable (variable, value, **EnvironmentVariableTarget**) Possible values are: *Machine*, *Process* and *User* – Lessan Vaezi Feb 13 '11 at 12:45
-
2Does `EnvironmentVariableTarget.Machine` requires Administrator access? – checksum Feb 11 '14 at 06:45
-
Yes, it does. Trying to run it without will result in an obvious exception. – Erez A. Korn May 13 '15 at 04:19
Get and Set
Get
string getEnv = Environment.GetEnvironmentVariable("envVar");
Set
string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);

- 19,633
- 6
- 111
- 113
-
Can I set Environment Variable not programmatically? Trough project properties for example – Igor Markiv Apr 20 '23 at 11:27
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.

- 8,924
- 5
- 35
- 29
-
8+1 I had to use this solution because the other one answered by Patrick Desjardins required me to have admin privileges. I was able to read the value of the environment variable without having admin privileges with this solution! – Tono Nam Apr 18 '13 at 15:07
-
@TonoNam Patrick’s answer works in my machine *without* admin privileges. Note that setting System environment variable does require admin privileges (of course). – Franklin Yu Oct 31 '18 at 00:33
-
what about getting the `PATH` variable of the *current user* instead of the _machine_, how to do that? – JobaDiniz Apr 18 '23 at 10:44
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);

- 8,861
- 2
- 30
- 34

- 371
- 3
- 14
Environment.SetEnvironmentVariable("Variable name", value, EnvironmentVariableTarget.User);

- 5,465
- 5
- 30
- 60
-
1If you want your PATH variable to be permanent use `EnvironmentVariableTarget.Machine` instead. – Daniel Bonetti Sep 26 '13 at 16:08
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();
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.

- 1,330
- 1
- 11
- 31
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);

- 9,442
- 5
- 47
- 90
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);

- 11
- 3
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>

- 1,613
- 17
- 24
-
This misses the advantage of using environment variable - this snippet "hardcodes" the connection string in the config file, instead of relying on an environment variable. – OfirD Aug 09 '21 at 07:07
-