문제

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

도움이 되었습니까?

해결책

Your code should be

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top