I'm creating an extension for visual studio and one of the requested feature is that it is able to change an environment variable to one of several options, which will then be inherited by the application being developed once it is debugged.
I have tried the following
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine);
but while that persists the variable, it does not seem to pass it on to the program once I hit run.
I'm looking for other ways of doing this to try, and I don't mind if they're hacky.
Edit: For clarification, this process should be transparent to the (arbitrary) program being debugged. It must also be a programmatic solution
To access this page, select a project node in Solution Explorer, select Project > Properties from the Visual Studio menu, and then select the Environment Variables tab. Specifies the name of an environment variable that will be used when the project is built or when the project is run from Visual Studio.
You can use compilation constants. Define a class that is responsible to retrieve your variables:
public class MyEnvironment {
public string SomeVariable{
get{
#if DEBUG
return "bar";
#else
return Environment.GetEnvironmentVariable("foo");
#endif
}
}
}
You may also use some kind of IOC to inject a variable provider instance. Either a "production" version that reads the environment, or a debug version with hard coded values.
I have a guess why the program you are debugging doesn't get your environment variables. A process reads the environment variables at process startup. And if you are developing a .NET application Visual Studio create a *.vshost.exe process in order to speed up the debugging startup. So Visual Studio does not create start a new process when you start debugging - with the result that your environment variables are not read.
In stead you could use a memory mapped file to do the required IPC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With