How do you create and set environment variables?

  • Thread starter Thread starter Ron Clarke
  • Start date Start date
R

Ron Clarke

I have an application that starts other processes. The app needs to
create/set a few environment variables when a process starts, let the
process run, then remove the environment variables when the process
terminates. Looking through the C# and .NET docs, I've found how to get
environment variables, but not how to create and set them. I found the
EnvironmentPermissions class which grants access, but that's not enough.
Can anyone help me here; the functionality must be out there somewhere!
Thanks.
 
Hi Ron,
Take a look at Process and ProcessStartInfo classes. Using ProcessStartInfo
you can set envionment variables.
Each process has its own set of envirnment variables so, you don't have to
remove yours when the process terminates
 
Thanks, but I've already looked there. Unless the documentation is wrong,
you can only get the values, you cannot set them.
For example, the ProcessStartInfo.EnvironmentVariables property is defined
this way:
public StringDictionary EnvironmentVariables {get;}

I could get some variables and modify the dictionary contents, but then how
do I get them back into the environment if the property does allow a "set"?
For something that should be so simple, there must be a way to do it!

Thanks in advance,
Ron
 
Hi Ron,
You cannot change the invironment on already running process.
The set of envirnoment variables can be only changed upon process creation.

About the EnvironmentVariables property. The property itself is readonly
because it returns StringDictionary (collection) and you cannot set a new
collection. But you can modify (add, delete, change) its content.
Once you compose the set of environment variables you start the new process
using that ProcessStartInfo.
When the process is up and running no one can change its environment except
the process itself.
 
Aah, that makes more sense. For some reason it did not occur to me that the
contents of the EnvironmentVariables property might be able to be modified.
That's what I need. Thanks.

-Ron
 
Back
Top