[Solved] C# set environment variable

I have problem with setting environment variables using C#.

I need to modify some environment variables on some circumstances. For example I need to modify NDSRC variable.

I use:

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

This works fine.

Next i run some script whitch uses the variable. And now there is a problem, because script does not see the variable.

Example:
Set Path variable (add a directory at the end) using

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

Open windows command line (Start->run->cmd.exe).

In command line type cmd

The system can not find cmd.exe: ‘cmd’ is not recognized as an internal or external command, operable program or batch file.

If you check Windows settings – > Environment Variables, Path is correctly set to new value. If you check in opened command prompt, it is also set.

Solution #1:

Unfortunately, you need to restart your process before environment variables can be refreshed. See this MSDN post.

Respondent: Steve Danner

Solution #2:

It is by design that the variables are inherited when the process starts, and remain fixed after that.

However there is no reason why you can’t just go in to read the relevant registry keys periodically and update your process’ environment variables manually from that. In fact, this is the right thing to do if you’re after up-to-date values.

Basically, the registry stores a template for environment variables, and that’s what you edit via “Windows settings – > Environment Variables”. When you do that, Windows broadcasts a message to all interested parties. Any such parties can then re-create their copy of the environment variables from the registry.

I am not aware of any ready-made function that you can just call to perform this re-creation, however, so you’ll probably have to write your own.

Respondent: Roman Starkov

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.