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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With