Export (0) Print
Expand All

Environment.SetEnvironmentVariable Method (String, String)

Creates, modifies, or deletes an environment variable stored in the current process.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public static void SetEnvironmentVariable(
	string variable,
	string value
)

Parameters

variable
Type: System.String

The name of an environment variable.

value
Type: System.String

A value to assign to variable.

ExceptionCondition
ArgumentNullException

variable is null.

ArgumentException

variable contains a zero-length string, an initial hexadecimal zero character (0x00), or an equal sign ("=").

-or-

The length of variable or value is greater than or equal to 32,767 characters.

-or-

An error occurred during the execution of this operation.

SecurityException

The caller does not have the required permission to perform this operation.

Calling this method is equivalent to calling the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) overload with a value of EnvironmentVariableTarget.Process for the target argument.

If the value argument is not empty (see the discussion of deleting an environment variable later in this section for the definition of an empty value) and the environment variable named by the variable parameter does not exist, the environment variable is created and assigned the contents of value. If it does exist, its value is modified. Because the environment variable is defined in the environment block of the current process only, it does not persist after the process has ended.

If variable contains a non-initial hexadecimal zero character, the characters before the zero character are considered the environment variable name and all subsequent characters are ignored.

If value contains a non-initial hexadecimal zero character, the characters before the zero character are assigned to the environment variable and all subsequent characters are ignored.

If value is empty and the environment variable named by variable exists, the environment variable is deleted. If variable does not exist, no error occurs even though the operation cannot be performed. value is considered empty under any of the following conditions:

  • It is null.

  • It is String.Empty.

  • It consists of a single character whose value is U+0000.

The following example tests whether an environment variable named APPDOMAIN exists in the current process. If it does not, it creates it and sets its value to "True". If the value of the APPDOMAIN environment variable is "True", it calls the Message.Display method in a new application domain. Otherwise, it executes the Message.Display method in the current application domain.

using System;

public class Example
{
   public static void Main()
   {
      String envName = "AppDomain";
      String envValue = "True";

      // Determine whether the environment variable exists. 
      if (Environment.GetEnvironmentVariable(envName) == null)
         // If it doesn't exist, create it.
         Environment.SetEnvironmentVariable(envName, envValue);

      bool createAppDomain;
      Message msg;
      if (Boolean.TryParse(Environment.GetEnvironmentVariable(envName),
                          out createAppDomain) && createAppDomain) {
         AppDomain domain = AppDomain.CreateDomain("Domain2");
         msg = (Message) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, 
                                                        "Message");
         msg.Display();                                             
      }                                  
      else {
         msg = new Message();
         msg.Display();   
      }     
   }
}

public class Message : MarshalByRefObject
{
   public void Display()
   {
      Console.WriteLine("Executing in domain {0}", 
                        AppDomain.CurrentDomain.FriendlyName);
   }
}

If you run the example for the first time, the message "Executing in domain Domain2" displays to the console. If you set the environment variable from the command line by using the command:

Set AppDomain=False

the example displays the message "Executing in domain exeName.exe", where exeName is the name of the executable.

The following example attempts to retrieve the value of an environment variable named Test1 from the process environment block. If the variable doesn't exist, the example creates the variable and retrieves its value. The example displays the value of the variable. If the example created the variable, it also calls the GetEnvironmentVariables(EnvironmentVariableTarget) method with each member of the EnvironmentVariableTarget enumeration to establish that the variable can be retrieved only from the current process environment block. Finally, if the example created the variable, it deletes it.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      bool toDelete = false;

      // Check whether the environment variable exists. 
      value = Environment.GetEnvironmentVariable("Test1");
      // If necessary, create it. 
      if (value == null) {
         Environment.SetEnvironmentVariable("Test1", "Value1");
         toDelete = true;

         // Now retrieve it. 
         value = Environment.GetEnvironmentVariable("Test1");
      }
      // Display the value.
      Console.WriteLine("Test1: {0}\n", value);

      // Confirm that the value can only be retrieved from the process 
      // environment block.
      Console.WriteLine("Attempting to retrieve Test1 from:");
      foreach (EnvironmentVariableTarget enumValue in 
                         Enum.GetValues(typeof(EnvironmentVariableTarget))) {
         value = Environment.GetEnvironmentVariable("Test1", enumValue);
         Console.WriteLine("   {0}: {1}", enumValue, 
                           value != null ? value : "not found");
      }
      Console.WriteLine();

      // If we've created it, now delete it. 
      if (toDelete) { 
         Environment.SetEnvironmentVariable("Test1", null);
         // Confirm the deletion. 
         if (Environment.GetEnvironmentVariable("Test1") == null)
            Console.WriteLine("Test1 has been deleted.");
      }         
   }
}
// The example displays the following output: 
//       Test1: Value1 
//        
//       Attempting to retrieve Test1 from: 
//          Process: Value1 
//          User: not found 
//          Machine: not found 
//        
//       Test1 has been deleted.

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft