Reputation: 5366
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
Upvotes: 0
Views: 374
Reputation: 10055
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
Upvotes: 1
Reputation: 2093
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);
Upvotes: 1