The Vivandiere
The Vivandiere

Reputation: 3191

Can read but not update a newly created environment variable

I created a new environment variable to track the status of a possible failure condition, the variable is a simple flag called FailFlag that can be set or reset, with values FlagIsSet and FlagIsReset respectively. To create the environment variable I opened up system environment variables from Control Panel, and added a new system variable called FailFlag and assigned it value FlagIsReset.

Now, I want to programatically set and reset the flag from my C# program. I attempted this as follows :

namespace EnvVars
{
    class Program
    {
        static void Main(string[] args)
        {
            string value = Environment.GetEnvironmentVariable("FailFlag"); // Here value is seen to be 'FlagIsReset'
            if (value == null)
                System.Console.WriteLine("Failed to read env variable");  
            else
                Environment.SetEnvironmentVariable("FailFlag", "FlagIsSet");
        }
    }
}

But, if I run my program and then inspect my system environment variables again, I see that FailFlag is FlagIsReset rather than being FlagIsSet, which means that my program failed to update its value. Can you please suggest me a fix?

FWIW, I started Visual Studio as an administrator

Upvotes: 0

Views: 324

Answers (2)

glenebob
glenebob

Reputation: 1973

The environment is an inherited copy of the parent process' environment. You can't modify the global environment in the way you're trying to do.

Upvotes: 1

Nathan
Nathan

Reputation: 6531

Environment.SetEnvironmentVariable

Public method Static member     SetEnvironmentVariable(String, String)  //Creates, modifies, or deletes an environment variable stored in the current process.
Public method Static member     SetEnvironmentVariable(String, String, EnvironmentVariableTarget)   //Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.

Since the scope of that overload of SetEnvironmentVariable is the process, what did you expect?

Try a different environmentvariabletarget Enumeration if you want a different storage scope

Upvotes: 3

Related Questions