Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment.SetEnvironmentVariable not working

Tags:

c#

I have a simple C# console app that sets an environment variable. The line in question is:

Environment.SetEnvironmentVariable("testvar", args[0]);

I've checked and args[0] has a value in it.

When I run the compiled exe from the cmd prompt, there are no errors.

When I then use set testvar, I get an error saying that the environment variable is not defined.

By default, the SetEnvironmentVariable method sets it just for the process. So I'm thinking that it only exists for the lifetime of the exe. If that is the case, how do I set it for the life time of the cmd prompt?

Any ideas?

I'm targetting .NET 4

Another way of asking my question would be:

how do I get C# to store a value for the current cmd prompt that can be read after the exe file that set the value, has finished. More than one login under the same username, may be using this so storing the value somewhere may conflict with the other login.

like image 735
Graham Avatar asked Feb 18 '26 17:02

Graham


1 Answers

Sounds like you want the environment variable for the entire machine and not just this process.

Environment.SetEnvironmentVariable("testvar", args[0], EnvironmentVariableTarget.Machine);

Unfortunately you need to restart your process before environment variables are updated. C# set environment variable

It might suit you better to store the information in the registry or a file. It's all up to what your applications are capable of using but that might also be an option.

like image 105
Jason Geiger Avatar answered Feb 21 '26 09:02

Jason Geiger



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!