Logan Bender
Logan Bender

Reputation: 369

Changes with SetEnvrionmentVariable cant be read with GetEvironmentVaribale until reboot?

New to Envriroment Variable usage.

I am coding project setup tool and need to store some user specified project directory paths across sessions. Someone suggested Get/SetEvironmentVariable. So I set up a Windows Form with textBoxes to display the paths. When I load the form it uses GetEvironmentVariable, and the textBoxes populate as expected. but when I try to update values with SetEvironmentVariable , the textBoxes are empty and do not show the updated variable until rebooting.

    private void button1_Click(object sender, EventArgs e)
    {
        Environment.SetEnvironmentVariable("my_project_dir", "C:\path\to\my\project" , EnvironmentVariableTarget.Machine );
        textBox1.Text = Environment.GetEnvironmentVariable("my_project_dir", EnvironmentVariableTarget.Machine);
    }

Upvotes: 0

Views: 84

Answers (1)

Scott Dorman
Scott Dorman

Reputation: 42516

It's because you are setting the environment variable to be a machine-wide variable. See msdn for more details.

The environment variable is stored or retrieved from the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment key in the Windows operating system registry. When a user creates the environment variable in a set operation, the operating system stores the environment variable in the system registry, but not in the current process. If any user on the local machine starts a new process, the operating system copies the environment variable from the registry to that process.

When the process terminates, the operating system destroys the environment variable in that process. However, the environment variable in the registry persists until a user removes it programmatically or by means of an operating system tool.

The important part is this:

When a user creates the environment variable in a set operation, the operating system stores the environment variable in the system registry, but not in the current process.

What you want to do instead is use EnvironmentVariableTarget.Process (which is the default, so you don't need to specify anything), which will store the environment variable in the environment block associated with the current process.

Upvotes: 1

Related Questions