C# Environment variables

If you ever need to set environment variables in .Net 2.0+, you can use these:

"Somevalue", EnvironmentVariableTarget.Machine);

"Somevalue", EnvironmentVariableTarget.User);

"Somevalue", EnvironmentVariableTarget.Process);

string env_val = System.Environment.GetEnvironmentVariable(
"PROCESS_VAR", EnvironmentVariableTarget.Process);

These however do have their limitations:

  • If your use does not have privileges to the registry or to set environment variables these will not work. You will get an exception telling you so (in debug mode).
  • If you have a DLL that read environment variables you set, pay close attention to when your DLL is loaded, it might be loaded earlier than you think, so if you change these on the fly you will have to unload and reload your DLL. This is considered a bad practice to begin with since your code is not portable if it relies on environment variables.

Comments are closed.