0

I am trying to modify environmental variable using the below code.

Environment.SetEnvironmentVariable("MyEnv", "True");

In the same program in the next line, I am trying to retrive it.

string myEnv=Environment.GetEnvironmentVariable("MyEnv");

But I am getting the old value in the environment variable not the new value. Any pointers to the problem will be helpful. using c# and .Net4.0

Ayyappan Subramanian
  • 5,348
  • 1
  • 22
  • 44
  • 1
    I cannot replicate your problem in LinqPad. Is there more to your program that could be causing the issue? How are you observing the `myEnv` variable? – D Stanley Jan 26 '15 at 16:48
  • 1
    possible duplicate of [How to set system environment variable in C#?](http://stackoverflow.com/questions/19705401/how-to-set-system-environment-variable-in-c) – Oscar Jan 26 '15 at 16:50
  • Setting the environment variable is happening as per the above given link, but how about getting the new value in the next line. – Ayyappan Subramanian Jan 26 '15 at 16:53
  • The code you provided works in LinqPad (and I strongly suspect it works in VS as well). Either you are not observing the result properly or something else is affecting the result. – D Stanley Jan 26 '15 at 16:55

2 Answers2

1

Until your hosting process is restarted, its not going to recognize the new value unless you set the EnvironmentVariableTarget to "Process":

Environment.SetEnvironmentVariable("MyEnv", "True",EnvironmentVariableTarget.Process);
string myEnv=Environment.GetEnvironmentVariable("MyEnv",EnvironmentVariableTarget.Process);
David P
  • 2,027
  • 3
  • 15
  • 27
  • 1
    Your suggestion is identical to OP's code (`Process` is default for both calls) - not sure why you think explicitly specifying it helps. – Alexei Levenkov Jan 26 '15 at 17:17
  • Are you running the process as Administrator or with elevated privileges? If not, try that and let me know what happens. If it works in that case you might want to add requestedExecutionLevel to your signed application manifest. – David P Jan 27 '15 at 13:24
1

When storing environmental variables like this they are only stored as long as the process is running. If you close your program the variables are gone.

    static void Main(string[] args)
    {
        string MyEnv = string.Empty;

        MyEnv = Environment.GetEnvironmentVariable("MyEnv");
        Console.WriteLine("MyEnv=" + MyEnv);

        MyEnv = "True";
        Environment.SetEnvironmentVariable("MyEnv", MyEnv);
        MyEnv = Environment.GetEnvironmentVariable("MyEnv");
        Console.WriteLine("MyEnv=" + MyEnv);

        MyEnv = "False";
        Environment.SetEnvironmentVariable("MyEnv", MyEnv);
        MyEnv = Environment.GetEnvironmentVariable("MyEnv");
        Console.WriteLine("MyEnv=" + MyEnv);

        Console.ReadLine();
    }

Output:

MyEnv=
MyEnv=True
MyEnv=False
CathalMF
  • 9,705
  • 6
  • 70
  • 106