[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.
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.
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.
Unfortunately, you need to restart your process before environment variables can be refreshed. See this MSDN post.
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.