7

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

Anthony
  • 286
  • 3
  • 11

3 Answers3

5

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.

Steve B
  • 36,818
  • 21
  • 101
  • 174
4

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.

Morten Frederiksen
  • 5,114
  • 1
  • 40
  • 72
0

I don't know if the settings can be changed programattically, but I would take a look at this question: How do I set specific environment variables when debugging in Visual Studio?

If you are starting the process yourself, the StartInfo object that gets passed to Process.Start() has an EnvironmentVariables property that you could look into using as well.

Community
  • 1
  • 1
mageos
  • 1,216
  • 7
  • 15