1

Under Environment Variables for User, i have added a variable with the key called eg.

TMP_VAR

and value eg.

C:\temp\sim

When starting a new process in my C# application created in VS2010 .Net 4.0 and setting the StartInfo.EnvironmentVariables.Add("TMP_VAR", C:\temp\sim); I get this error when double clicking the exe file:

Item has already been added. Key in dictionary: 'TMP_VAR' Key being added: 'TMP_VAR'

If however I start it from VS2010 (pressing F5) no error occurs.

My theory is that VS2010 somehow starts the process in somekind of a "shell" and overwrites the variable in that "shell".

Also my application start several processes with the same key but different value. The key cannot be changed. It has to be TMP_VAR, but the value is allowed to be changed.

My question is: How can my application start a new process, setting the same key using StartInfo.EnvironmentVariables in somekind of a "shell". Or is there another smart solution to my problem?

Phu Minh Pham
  • 1,025
  • 7
  • 21
  • 38

1 Answers1

4

Instead of adding, processes can check the existence of the key 'TMP_VAR' and just change the value accordingly if it exists.

if(StartInfo.EnvironmentVariables.ContainsKey("TMP_VAR"))
    StartInfo.EnvironmentVariables["TMP_VAR"] = "C:/temp/sim";
else
    StartInfo.EnvironmentVariables.Add("TMP_VAR", "C:/temp/sim");
tafa
  • 7,146
  • 3
  • 36
  • 40
  • 3
    You don't need the if clause... StartInfo.EnvironmentVariables["TMP_VAR"] = "C:/temp/sim"; will add it if it doesn't exist, or overwrite it if it does – Martin Ernst May 23 '12 at 09:46
  • If the first process change the value and starts afterwards, what will happen when a second process changes the value and starts while the first process is running? – Phu Minh Pham May 23 '12 at 10:06
  • It seems to work anyway :) THX! but it'll be nice to know that happens anyway :) – Phu Minh Pham May 23 '12 at 10:28
  • If you want the processes to have their own values kept then maybe environment variables are not the best place to keep those values. AirTrickz, what will happen is all the processes will read the last value set. @Martin you are completely right. – tafa May 23 '12 at 10:30