Open In App

C# Environment Class SetEnvironmentVariable() Method With Examples

Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since last system boot in milliseconds information. This class provides different types of methods and properties and SetEnvironmentVariable() method is one of them. This method is used to create, delete, or modify the environment variable. This method is overloaded in two different ways:

1. SetEnvironmentVariable(String, String): By using the SetEnvironmentVariable() method we can create, delete, or modify the environment variable stored in the current process.



Syntax:

public static void SetEnvironmentVariable (string varstr, string? val);

Where this method takes two parameters named varstr and val. Here, varstr represents the name of the Environment variable and val represents a value to assign to varstr.



Exception: This method will throw the following exceptions:

2. SetEnvironmentVariable(String, String, EnvironmentVariableTarget): This method is used to modify, create, or delete an environment variable stored in the current process, or in the Windows OS registry key reserved for the current user or local machine.

Syntax:

public static void SetEnvironmentVariable (string varstr, string? val, EnvironmentVariableTarget t);

Where this method takes three parameters named varstr, val, and t. Here, varstr represents the name of the Environment variable, val represents a value to assign to varstr. And t represents the location of the environment variable.

Exception: This method will throw the following exceptions:

Example:




// C# program to illustrate the use of 
// SetEnvironmentVariable() method 
using System;
using System.IO;
  
class GFG{
      
static public void Main()
{
      
    // Declare variable 
    string variable = "Geeks";
      
    // Declare value
    string value = "True";
      
    // Check whether the value stored in environment variable
    if (Environment.GetEnvironmentVariable(variable) == null)
    {
        Environment.SetEnvironmentVariable(variable, value);
        Console.WriteLine("In environment variable, the value is stored");
    }
    else
    {
        Console.WriteLine("In environment variable, the value is already stored");
    }
}
}

Output:

In environment variable, the value is stored

Article Tags :
C#