Is it possible to persist an environment variable in a console application which is available after the process has exited.
I want a console application to set a string which is available to the batch file which executed it.
The console application is in dotnet.
You can use Environment.SetEnvironmentVariable:
The last parameter will determine the scope and lifetime of the variable (either Process, User or Machine). If you want to set the variable for the machine you will need to run as admin.
Edit: I do notice though that if executing a console application with the above code, the environment variable is not available until you open a new command window (so if executing the console app from a batch file, the variable will not be available to the batch file, unless there is a trick to have it refresh the set of environment variables that it sees).
Edit 2: OK, I was digging around with this and there seem to be no obvious way to have the batch file get a refreshed set of environment variables. One workaround that I found is to to have the .net code write a batch file for setting the variables, instead of setting them itself. The calling batch script can then run the created batch file to have the environment set up:
.Net Console App:
BAT-file: