Amazon.com Widgets

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....

Published 23 February 04 09:29 by BradA
Filed under:

Comments

# Junfeng Zhang said on February 23, 2004 11:07 PM:
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.
# Tom McKearney said on February 24, 2004 4:27 AM:
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 :)
# Enjoy Every Sandwich said on February 24, 2004 9:12 PM:
Take Outs: The Digital Doggy Bag of Blog Bits for 24 February 2004
# Mark Olson's blog said on March 3, 2004 10:12 PM:
# C# Frequently Asked Questions said on December 2, 2004 12:03 PM:
New Comments to this post are disabled

Search

This Blog

Syndication

Page view tracker