Question

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

Was it helpful?

Solution

Your code should be

if(!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("qwert")))
    Console.WriteLine(Environment.GetEnvironmentVariable("qwert"));
Console.WriteLine("hello");

OTHER TIPS

Try This:

 if(Environment.GetEnvironmentVariable("qwert") != null 
       && !Environment.GetEnvironmentVariable("qwert").ToString().Equals("null"))

The easiest way is to log out and in again. Environment variable changes on the system level (e.g. the dialog you're using there) are picked up by Explorer only by default and no other running process picks up the change. So either launch your program again (and if you start it from VS, restart Visual Studio first) or just log out once and log in again to get a clean slate.

Variable value: null does not mean null actually. I think you should leave it blank to get a C# equivalent null value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top