I have a C# console application that I compiled for Linux. The application needs to access environment variables. I tried setting it up using EXPORT var1=value1 or by setting it in /etc/environment. I see the environment variable is set correctly when I do printenv, but when my application runs it can't access the variable.
Can someone suggest how to make my application access environment variables? I am running it on RHEL 8 and in my application, I am accessing environment variable using Environment.GetEnvironmentVariable
Here is a code to demonstrate it:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var env = Environment.GetEnvironmentVariable("HOMEBREW_PREFIX");
Console.WriteLine($"In worker process: {env}");
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
Here is a partial output from printenv that shows environment variable called HOMEBREW_PREFIX set correctly.
HOMEBREW_PREFIX=/opt/homebrew HOMEBREW_CELLAR=/opt/homebrew/Cellar
Here is screenshot at the breakpoint and my watch window:
This happens on both my mac and my RHEL box. Environment.GetEnvironmentVariable() return null and can't access environment variables.
There is yet another question that seems to be doing similar things, but I am trying to access an environment variable which already exists, while the other one is trying to set it.
How can I fix this?


Try using version of this method, which supports target as the second argument. It can be, that these environment variables are not visible to process target.