tags:

views:

30

answers:

1

I was trying to use the sentence

Environment.SetEnvironmentVariable("CLIENTIP", <value>)

but the variable is not created. I used both an string variable and a constant to set the value.

So, how can I do this to work?

+2  A: 

Can you explain what you mean by didn't work? That code will certainly set the environment variable CLIENTIP for the current process.

If you wanted to set it more broadly you're going to have to use a different overload of the SetEnvironmentVariable method.

Environment.SetEnvironmentVariable(
  "CLIENTIP", 
  value, 
  EnvironmentVariableTarget.Machine);

The EnvironmentVariableTarget parameter lets you target the process, machine or current user.

Note: These changes likely won't show up in existing processes as not all types of processes respond to this change immediately (cmd.exe is one that comes to mind). But it will show up on future processes.

JaredPar
Afaik the only process adapting to the change immediately is Explorer since that's the one launching processes.
Joey
That's probably the key. Environment variables have more than one copy. Try starting two command lines. In the 1st run `set test=123` then `set`. You'll see `test` exists. In the 2nd run `set`. `test` does not exist. They each have their own "working copy" of the environment variables. When a process starts, it will have a copy of the parent process variables, but then they will be independent. Both command line processes started with the same variables (from explorer.exe?). Any changes only affect itself and any future child processes.
Nelson