简体   繁体   中英

Why environment variable does not change?

I have Windows 7 and I am using this code:

        string genericLib = ConfigurationManager.AppSettings["GenericLib"];
        if (!string.IsNullOrEmpty(genericLib))
        {
            string path = Environment.GetEnvironmentVariable("Path");

            if (path != null && !path.Contains(genericLib))
            {
                path = genericLib + ";" + path;
                Environment.SetEnvironmentVariable("path", path);
            }

            string new_path = Environment.GetEnvironmentVariable("Path");
        }

Debugger shows me that new_path variable does contain new path that I added. But next time when I execute this code added path is no longer there.

Does someone know why is that?

The documentation of that method says (emphasis mine):

Creates, modifies, or deletes an environment variable stored in the current process .

So you are changing the environment variable for the process only. Use this overload instead:

Environment.SetEnvironmentVariable("path", path, EnvironmentVariableTarget.Machine);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM