Share via


More on Setting Environment variables

We had an internal thread about Setting Environment variables and someone posted a cool V1\V1.1 solution.

One workaround is to use System.Management (WMI). This should work on all versions of .NET Framework with WMI installed on the OS. You would retrieve the instance of the WMI Win32_Environment class, change the value, and commit. E.g.

To change a local system environment variable:

string envPath = "Win32_Environment.Name='SystemVariableNameHere'" + ",UserName='<SYSTEM>'";

ManagementObject envObject = new ManagementObject(envPath);

envObject["VariableValue"] = "NewSystemVariableValueHere";

envObject.Put(); // Save the change to the system

To change a local user environment variable:

string domainAlias = "DomainNameHere\\AliasHere";

string envPath = "Win32_Environment.Name='UserVariableNameHere'" + ",UserName='" + domainAlias + "'";

ManagementObject envObject = new ManagementObject(envPath);

envObject["VariableValue"] = "NewUserVariableValueHere";

envObject.Put();

To change an environment variable on a remote box, you would supply a ManagementScope object with connection configurations to the ManagementObject constructor.

You just have to love WMI....

Comments

  • Anonymous
    February 23, 2004
    I just want to point out, if you don't have any other dependency on WMI, you 're better off P/Invoking Win32 SetEnvironmentVariable. The first call to WMI is very expensive. It will start wmiprvse.exe, then use inter-process communicate to do all the work. Subsequent WMI calls will be faster, but still nowhere near the performance of SetEnvironmentVariable.

    As I see WMI, it is a wonderful thing for management. But you probably don't want to use it to do trivial things in your application.
  • Anonymous
    February 23, 2004
    Junfeng says: "As I see WMI, it is a wonderful thing for management. But you probably don't want to use it to do trivial things in your application."


    So, apparently I don't have to love WME :)
  • Anonymous
    February 24, 2004
    The comment has been removed