Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Environment variables permanently in C#

I am using the following code to get and set environment variables.

public static string Get( string name, bool ExpandVariables=true ) {
    if ( ExpandVariables ) {
        return System.Environment.GetEnvironmentVariable( name );
    } else {
        return (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" ).GetValue( name, "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames );
    }
}

public static void Set( string name, string value ) {
    System.Environment.SetEnvironmentVariable( name, value );
}

The problem I face, is even when the program is running as administrator, the environment variable lasts only as long as the program is running. I have confirmed this by running a Get on the variable I set in a previous instance.

Example usage of above

Set("OPENSSL_CONF", @"c:\openssl\openssl.cfg");

And to retrieve

MessageBox.Show( Get("OPENSSL_CONF") );

While the program is running, after using Set, the value is returned using Get without any issue. The problem is the environment variable isn't permanent (being set on the system).

It also never shows up under advanced properties.

Thanks in advance.

like image 635
Kraang Prime Avatar asked Jun 09 '15 07:06

Kraang Prime


2 Answers

While the program is running, after using Set, the value is returned using Get without any issue. The problem is the environment variable isn't permanent (being set on the system).

Thats because the overload of SetEnvironmentVariable that you're using stores in the process variables. From the docs:

Calling this method is equivalent to calling the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) overload with a value of EnvironmentVariableTarget.Process for the target argument.

You need to use the overload specifying EnvironmentVariableTarget.Machine instead:

public static void Set(string name, string value) 
{
    Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Machine);
}
like image 93
Yuval Itzchakov Avatar answered Sep 28 '22 10:09

Yuval Itzchakov


According to MSDN the method you are using is just modifying the variable for the runtime of the process.

Try the overload described here: https://msdn.microsoft.com/library/96xafkes%28v=vs.110%29.aspx

like image 24
ChrisM Avatar answered Sep 28 '22 12:09

ChrisM