Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload Environment Variables in C# after launch

We received a new code base that uses environment variables all over the place. They point to things like the project root, assets, different tools, etc. Not the most ideal situation but it works. However, when it comes time to try and run our automated build it becomes a giant pain.

Windows seems to instance the environment variables when a process is created and does not refresh those values again. We would like to be able to have our Automated Build System run through a list of projects and build each one sequentially. This requires calling a project switcher which changes those values. When this is done however the changes are not reflected in the currently running build process.

Does anyone know of any C# commands/functions/etc that can be used to force the environment variables to reload after the call to project switcher has been made?

like image 698
Motie Mediator Avatar asked Sep 01 '09 17:09

Motie Mediator


3 Answers

There are overloads of System.Environment.GetEnvironmentVariable and System.Environment.GetEnvironmentVariable that retrieve :

... the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.

If your changes affect the registry in the areas specified, this might work for you.

like image 66
JeffH Avatar answered Nov 14 '22 22:11

JeffH


According to MSDN:

"Altering the environment variables of a child process during process creation is the only way one process can directly change the environment variables of another process. A process can never directly change the environment variables of another process that is not a child of that process."

If the project switcher is not too complicated you could simply set the environment variables in the current process (e.g. using Environment.SetEnvironmentVariable or ProcessStartInfo.EnvironmentVariables).

like image 27
Special Touch Avatar answered Nov 14 '22 20:11

Special Touch


If you were to open a command prompt (cmd.exe) and then change the environment variables, that instance of cmd.exe will not see those changes. If you were to open a new instance of cmd.exe, that one will see the new changes. (Provided you changed the users environment variables and not the system ones).

I don't know how to mimic this in .NET. What you could try is create a new AppDomain and see if that works.

If it doesn't, you could try and see what happens if you create a new instance of your assembly by starting a new Process. In your case it could mean that you have to change the Automated Build System to fire builds of a new project as a new process.

I know these aren't straight answers, but perhaps they give you an idea on how to proceed.

like image 44
Guillaume Hanique Avatar answered Nov 14 '22 21:11

Guillaume Hanique