samnaction
samnaction

Reputation: 1254

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

Upvotes: 4

Views: 10235

Answers (4)

amiry jd
amiry jd

Reputation: 27575

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

Upvotes: 0

Joey
Joey

Reputation: 354346

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.

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Your code should be

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

Upvotes: 13

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26189

Try This:

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

Upvotes: 0

Related Questions