3

I know that to get environment variables with .NET Core the library to use theoretically is the System.Environment with the method GetEnvironmentVariable("environmentVariableKeyHere"). However, on Linux (Ubuntu 18.04) this isn't picking up my user based environment variables. I set the variables export THEVARIABLE="THEVALUE" and the .NET Core lib library and method won't pick it up. I even used the GetEnvironmentVariables() method and reviewed the entire list that it does pick up. None of the user environment variables where/are in that list.

I run a simle echo $THEVARIABLE in the terminal via bash and boom, the variable is there. The value is returned as expected, but still nothing via the .NET Program. Speaking of which, the repo is right here > https://github.com/Adron/InteroperabilityBlackBox if you'd like to check it out. It's built with Rider + .NET Core 2.1 and includes a library (is that an issue when running and trying to get user environment variables?), console app, and test library.

Adron
  • 1,698
  • 3
  • 19
  • 40

2 Answers2

3

According to the docs:

On MacOS and Linux, the GetEnvironmentVariables method retrieves the name and value of all environment variables that are inherited from the parent process that launched the dotnet process or that are defined within the scope of the dotnet process itself. Once the dotnet process ends, these latter environment variables cease to exist.

.NET Core does not support per-machine or per-user environment variables.

Community
  • 1
  • 1
NotMyself
  • 29,209
  • 17
  • 56
  • 74
  • 1
    Not sure if I'm understanding this correctly. Does this mean that we cannot specify a global environment variable on a Unix machine? For example, if I develop all applications on one Linux machine - can I set an `ASPNETCORE_ENVIRONMENT` variable on the machine, or does each of my applications have to specify this (for example, in vscode's launch.json)? – devklick Dec 23 '20 at 11:36
  • Hey @devklick no, one can definitely set a global environment variable or user specific. It's just different than the normal .NET landscape on a Windows machine and this left me looking in the wrong places for this issue. – Adron Dec 02 '21 at 19:39
0

It appears that things execute out of user session with Jetbrains Rider, which I was using for this code and initial development of this project. I've since figured out two solutions. One, environment variables can be added to most projects in Jetbrains Rider so that they execute and are available in that particular session. If using Visual Studio Code or just executing from the Bash Terminal then the values for the user session are of course available.

Adron
  • 1,698
  • 3
  • 19
  • 40