C# Program to Show the Use of GetEnvironmentVariable() Method of Environment Class


The GetEnvironmentVariable() method of the Environment class in C# is used to get the value of an environment variable. It is a useful method for retrieving system-wide and user-specific environment variables. In this article, we will discuss the usage of the GetEnvironmentVariable() method and see how to use it in a C# program.

What is the GetEnvironmentVariable() Method?

The GetEnvironmentVariable() method is a static method of the Environment class in C#. It takes the name of an environment variable as a string and returns the value of the variable as a string. If the environment variable does not exist, it returns null.

Syntax of GetEnvironmentVariable() Method

public static string GetEnvironmentVariable(string variableName)

Example: Using GetEnvironmentVariable() Method to get the Value of an Environment Variable

Let's see an example of how to use the GetEnvironmentVariable() method to get the value of an environment variable.

string path = Environment.GetEnvironmentVariable("Path");
Console.WriteLine("Path: " + path);

In this code, we use the GetEnvironmentVariable() method to retrieve the value of the "Path" environment variable.

Example: Using GetEnvironmentVariable() Method to get the Value of a Custom Environment Variable

Now, let's see an example of how to use the GetEnvironmentVariable() method to retrieve the value of a custom environment variable.

using System;

class Program {
   static void Main() {
      string customVariable = Environment.GetEnvironmentVariable("CustomVariable");
   
      if (!string.IsNullOrEmpty(customVariable)) {
         Console.WriteLine("CustomVariable: " + customVariable);
      } else {
         Console.WriteLine("CustomVariable does not exist");
      }
   }
}

Output

CustomVariable does not exist

In this code, we use the GetEnvironmentVariable() method to retrieve the value of a custom environment variable named "CustomVariable". We then output the value of the variable to the console. If the variable does not exist, we output a message indicating that the variable does not exist.

Conclusion

The GetEnvironmentVariable() method of the Environment class is a powerful method that can be used to retrieve the value of an environment variable in C#. In this article, we discussed the usage of the GetEnvironmentVariable() method and saw how to use it in a C# program to get the value of both system-wide and user-specific environment variables.

Updated on: 04-May-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements