In C#, the GetEnvironmentVariable() method of the Environment class is used to obtain the value of the 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 GetEnvironmentVariable() method and understand how to use it in C# program.
The GetEnvironmentVariable() method is a static method of the Environment class in C#. It takes the name of the environment variable as a string and returns the variable's value as a string. If the environment variable does not exist, null is returned.
public static string GetEnvironmentVariable(string variableName)
Let's look at an example that demonstrates 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 get the value of the "Path" environment variable.
Now, let's look at an example that demonstrates 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"); } } }
CustomVariable does not exist
In this code, we use the GetEnvironmentVariable() method to retrieve the value of the custom environment variable "CustomVariable". We then print the variable's value to the console. If the variable does not exist, a message indicating that the variable does not exist is output.
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 GetEnvironmentVariable() method and saw how it can be used in C# programs to get the values of system-wide and user-specific environment variables.
The above is the detailed content of C# program displays the use of the GetEnvironmentVariable() method of the environment class. For more information, please follow other related articles on the PHP Chinese website!