Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding whether environment variable is defined or not in C#

Here is my code to check whether environment variable is defined or not

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            if(Environment.GetEnvironmentVariable("qwert")==null)
            Console.WriteLine(Environment.GetEnvironmentVariable("qwert"));
        Console.WriteLine("hello");
        }
    }
}

But the problem is if I set my environment variable value as null it is executing the if statement. What is the workaround for this? The code should work for both the conditions any variable value is set or it is set as null.

enter image description here

like image 461
samnaction Avatar asked Oct 15 '25 08:10

samnaction


1 Answers

Your code should be

if(!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("qwert")))
    Console.WriteLine(Environment.GetEnvironmentVariable("qwert"));
Console.WriteLine("hello");
like image 173
Nikhil Agrawal Avatar answered Oct 16 '25 22:10

Nikhil Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!