How can I get Environnment variables and if something is missing, set the value?
Use the System.Environment class.
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
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:
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.