61

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lemmerich
  • 1,222
  • 1
  • 10
  • 13

7 Answers7

94

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

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Branden Barber
  • 1,717
  • 1
  • 17
  • 15
  • 19
    VS apparently doesn't detect changes to the environment variables while it is running. Knowing this would have saved me a ton of pointless troubleshooting. This answer should be higher on the list. – Flopdong Jul 13 '18 at 17:49
  • what an easy fix this has been. I was just overlooking this one but boy, this solved my problem. Thanks for the simple yet helpful suggestion! – theITvideos Aug 12 '18 at 13:30
  • Not sure why exactly but this worked for me as well. Oddly enough in my DBContext class I did not have this issue, but in Startup.cs (using `EnvironmentVariableTarget.Process`) I was not able to find the Environment variable unless I used `EnvironmentVariableTarget.User/Machine`. After restarting Visual Studio, I was able to find the value using any of the 3 enumerations. – Brien Foss Nov 06 '18 at 02:08
  • Windows `cmd.exe` (aka cmd or Command Prompt), on which PowerShell is built, caches all environment variables when it loads. – Abel Wenning Mar 02 '21 at 20:52
  • 3
    Rider 2021.2.1 also has this issue. – harvzor Oct 12 '21 at 10:22
  • 2
    If you are using Rider, it's the same. Restart Rider and it will pick up the user variables. – RichArt Dec 07 '21 at 15:51
51

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Patrick Michalina
  • 1,279
  • 2
  • 12
  • 15
  • 1
    This actually works for system var also. Just change the .User to .Machine. I was appending to PATH var, and it wasn't getting the set value from codeline using just Environment.GetEnvironmentVariable("PATH") changing to Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) retrieved the new value. – Zunair Jul 07 '17 at 15:57
  • This worked for me too. Without it, I had to restart my system, even though I had added a user variable. – Tamra Myers - Microsoft Mar 01 '18 at 21:11
30

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.

PBMe_HikeIt
  • 659
  • 8
  • 24
sergserg
  • 21,716
  • 41
  • 129
  • 182
  • 1
    That is the problem, the variable exists both at system and user level at the host machine =/ . I created an console app just to check the variable and it works (shows the value i expect) but when i call a ws hosted on iis on that same machine the same method returns empty value. – Lemmerich Oct 08 '12 at 13:21
  • 12
    Oh c*** and all i needed was to restart the server... my app was getting value set at user level. Makes sense now. Thanks! – Lemmerich Oct 08 '12 at 14:06
  • 1
    Glad to hear your figured it out. If you want, edit my answer and add in your warning about restarting the server and why you needed to restart it. This answer might help other people. – sergserg Oct 08 '12 at 14:09
  • 1
    I faced a similar issue where I added some custom environment variables and Environment.GetEnvironmentVariable("custom_variable") was not reading it. I restarted the system and same piece of code worked. – sabertooth1990 Oct 07 '13 at 05:39
  • What do you mean by ***invoking*** an environment variable? How can an environment variable be invoked? – Peter Mortensen Feb 27 '20 at 22:25
19

You need to restart IIS by using the iisreset command.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
haishan
  • 355
  • 2
  • 3
0

There's a DLL or some code snipped that is shared by cmd, PowerShell, and Visual Studio (maybe also by VS Code) that caches environment variables (separately for each app) when they load.

So, if you are testing something for which you're changing environment variables, instead of restarting your IDE (which is slow), you can just start a separate cmd or PowerShell to test, change environment variables, and then just restart that cmd or PowerShell. I recommend PowerShell because you can use the up arrow to reuse commands typed in previous sessions.

Abel Wenning
  • 483
  • 8
  • 6
0

My project's csproj file did not have (or expected) the local.settings.json. By adding it's update node, the Environment.GetEnvironmentVariable("variablename") started working and fetching the information from variables.

<ItemGroup>
    <None Update="host.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
</ItemGroup>
Arthur Zennig
  • 2,058
  • 26
  • 20
0

I got same issue. If the Environment.GetEnvironmentVariable() doesn't work, just set the value of it in the program.cs file. In my case i had the value in the appsettings.json file, so i could set the value in program.cs like this:

Environment.SetEnvironmentVariable("ASPNETCORE_APIURL", builder.Configuration.GetSection("Urls").GetSection("APIUrl").Value);