March 24, 2010

Environment Variables

Environment.SetEnvironmentVariable Method on MSDN provides some comprehensive samples

Use of "Environment.GetEnvironmentVariables()" Example:
...
  ShowEnvironmentVariables(EnvironmentVariableTarget.User);
  ShowEnvironmentVariables(EnvironmentVariableTarget.Machine);
  ShowEnvironmentVariables(EnvironmentVariableTarget.Process);
...
private static void ShowEnvironmentVariables(EnvironmentVariableTarget targ)
{
    IDictionary ret = Environment.GetEnvironmentVariables(targ);
    string[] keys = new string[ret.Count];
    string[] values = new string[ret.Count];
    ret.Keys.CopyTo(keys, 0);
    ret.Values.CopyTo(values, 0);

    string targStr = targ.ToString().ToUpper();
    string underlineStr = "=======";
    Debug.WriteLine(targStr);
    Debug.WriteLine(underlineStr);
    for (int ix = 0; ix < ret.Count; ix++)
    {
        Console.WriteLine(keys[ix] + " = " + values[ix]);
    }
    Debug.WriteLine("");
}
To write an Environment variable use "Environment.SetEnvironmentVariable"
// by default the environment variable is set on the "Process"
Environment.SetEnvironmentVariable("TestEnvVar", "change1");
// but can be set for the user
Environment.SetEnvironmentVariable("TestEnvVar", "andagain", EnvironmentVariableTarget.User);
// or the system (if the program is executed through an account 
// with the appropriate permissions)
Environment.SetEnvironmentVariable("TestEnvVar", "andagain", EnvironmentVariableTarget.Machine);