Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.


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.


Get and Set

Get

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

Set

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

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);

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

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>