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

Mister Dev picture Mister Dev · Oct 9, 2008 · Viewed 191.3k times · Source

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

Answer

Patrick Desjardins picture Patrick Desjardins · Oct 9, 2008

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.