C # environment variable

I have a problem setting environment variables using C #.

I need to change some environment variables in some circumstances. For example, I need to change the NDSRC variable.

I use:

Environment.SetEnvironmentVariable("MY_VARIABLE", "value", EnvironmentVariableTarget.Machine); 

This works great.

Then I run some script whitch uses a variable. And now there is a problem because the script does not see the variable.

Example: Set the Path variable (add a directory to the end) with

 string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine) + ";c:\\"; Environment.SetEnvironmentVariable("Path", path, EnvironmentVariableTarget.Machine); 

Open the Windows command prompt (Start-> run-> cmd.exe).

At the command prompt, type cmd

The system cannot find cmd.exe: 'cmd' is not recognized as an internal or external command, operating program, or batch file.

If you check the settings of Windows -> Environment Variables, Path will be correctly set to the new value. If you close the open command line, it will also be installed.

+8
c # environment-variables
source share
2 answers

Unfortunately, you need to restart your process before environment variables can be updated. See This MSDN Message.

+4
source share

By design, the variables are inherited when the process starts and remain fixed after that.

However, there is no reason why you cannot just reuse the appropriate registry keys and manually update process environment variables. In fact, this is the right thing to do if youre after the last values.

Basically, a template for environment variables is stored in the registry, and this is what you are editing using β€œWindows Settings β†’ Environment Variables”. When you do this, Windows broadcasts the message to all interested parties. Any such parties can then recreate their copy of the environment variables from the registry.

I am not aware of any ready-made function that you can simply call to recreate, so you may have to write your own.

+1
source share

All Articles