Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set/Get command line system variables in C#

When I open a windows command prompt and type "set" then enter, I get a list of system variables.

How do I set/get those in C# using visual studio?

I tried:

System.Environment.SetEnvironmentVariable("TestVariableName", "test123");

However, when I type "set" into the command line, I don't see my new variable called "TestVariableName" with value of "test123".

What am I doing wrong?

Thanks

like image 675
user952342 Avatar asked Mar 29 '26 00:03

user952342


1 Answers

First off, the overload of SetEnvironmentVariable that you used "Creates, modifies, or deletes an environment variable stored in the current process." ( http://msdn.microsoft.com/en-us/library/system.environment.setenvironmentvariable.aspx?ppud=4 ).

You should use this overload with an EvironmentVariableTarget value of Machine if you want it to affect other programs.

Secondly, environment variables are copied from the system or the parent process when a process starts, and never change from the perspective of a running application even if they are changed in the wider system.

In your case, start a new instance of the command line after setting the variable and you should see your variable.

like image 193
Chris Shain Avatar answered Apr 02 '26 03:04

Chris Shain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!