Environment.GetEnvironmentVariable won't find variable value

Why won't Environment.GetEnvironmentVariable("variableName") get a variable's value if the call is made from within a webMethod hosted on IIS and it will work if I call it from a console application on the same machine?

Where do I set up those variables to be visible to IIS web services? Should I use the second parameter from Environment.GetEnvironmentVariable(name, target) to get it?

It is actually really simple:

[WebMethod(Description = "Gets the environment variable value.")]
public string GetEnvironmentVariable()
{
    return Environment.GetEnvironmentVariable("VARIABLE_NAME_HERE");
}

And by the way, VARIABLE_NAME_HERE is set at the system and user level.


Solution 1:

Restarting Visual Studio fixed it for me (guessing IIS Express also caches these values).

Solution 2:

I faced the same issue, and thanks to sergserg's answer, I came up with this and it worked:

var value = Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User)

The important bit was using EnvironmentVariableTarget.User

Solution 3:

Read here for more information:

Using System Wide Environment Variables in .NET Application


Specifically:

What Are System Environment Variables?

Environment variables are strings that save information about the entire environment in your system. These string values are dynamic and they can affect the way your system will behave on. Environment variables can be classified into two main types:

System Variables: They affect the entire system whatever the current user is. They are defined by Windows and saved in the registry. You need to be an administrator to be able to modify them. You usually need to restart your computer to make these changes effective.

User Variables: They affect the current environment of the current system user. They can be deleted, modified, and added by any system user. They are used by Windows setup, by some programs, and by users. Changes to these variables are saved to the registry and be effective immediately.


If you try to access an environment variable that does not exist on your machine you will have issues. You must be trying to find a variable that exists on your local machine, but not on your web service's host machine.

Solution 4:

You need to restart IIS by using the iisreset command.