Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Visual Studio's environment variables for debugging a project

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

like image 848
Anthony Avatar asked Oct 07 '13 15:10

Anthony


People also ask

How do I set Environment Variables in Visual Studio?

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.


2 Answers

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.

like image 173
Steve B Avatar answered Oct 13 '22 06:10

Steve B


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.

like image 26
Morten Frederiksen Avatar answered Oct 13 '22 05:10

Morten Frederiksen