System.Environment.SetEnvironmentVariable 方法 (String, String, EnvironmentVariableTarget)

方法描述

创建、修改或删除当前进程中或者为当前用户或本地计算机保留的 Windows 操作系统注册表项中存储的环境变量。

语法定义(C# System.Environment.SetEnvironmentVariable 方法 (String, String, EnvironmentVariableTarget) 的用法)

public static void SetEnvironmentVariable(
	string variable,
	string value,
	EnvironmentVariableTarget target
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
variable System-String 环境变量名。
value System-String 要分配给 variable 的值。
target System-EnvironmentVariableTarget EnvironmentVariableTarget 值之一。
返回值 void

提示和注释

如果 value 参数不为空并且 variable 参数命名的环境变量不存在,则会创建该环境变量并为其分配 value 的内容。 完全为此操作考虑,如果 value 为 null、包含零长度字符串或包含起始十六进制零字符 (0x00),则此参数视为空。

如果 variable 包含非起始十六进制零字符,则零字符之前的字符将被视为环境变量名称,而且所有后续字符都将被忽略。

如果 value 包含非起始十六进制零字符,则零字符之前的字符将被分配给环境变量,而且所有后续字符都将被忽略。

如果 value 为空且 variable 命名的环境变量存在,则删除该环境变量。 如果 variable 不存在,则即使无法执行该操作也不会发生错误。 当 target 为 Machine 时应注意,因为有可能会删除影响整个本地计算机而不仅仅是影响当前进程或用户的环境变量。

如果 target 为 User,则环境变量存储在为当前用户保留的 Windows 注册表项中。 它还将复制到以当前用户身份运行的 Windows 资源管理器的实例。 然后,用户从 Windows 资源管理器启动的任何新进程将继承该环境变量。

同样,如果 target 为 Machine,则环境变量存储在为本地计算机保留的 Windows 注册表项中。 它还将复制到 Windows 资源管理器的所有实例。 然后,从 Windows 资源管理器启动的任何新进程将继承该环境变量。

如果 target 为 User 或 Machine,则 Windows WM_SETTINGCHANGE 消息将向其他应用程序通知 SET 操作。

如果 target 为 User 或 Machine,则建议 value 的长度小于 2048 个字符。

System.Environment.SetEnvironmentVariable 方法 (String, String, EnvironmentVariableTarget)例子

下面的示例创建 Process、User 和 Machine 目标的环境变量,并检查操作系统注册表是否包含 User 和 Machine 环境变量,然后删除环境变量。

// This example demonstrates the 
//     Environment.GetEnvironmentVariable,
//     Environment.SetEnvironmentVariable, and 
//     Environment.GetEnvironmentVariables overloaded methods.

using System;
using System.Collections;
using Microsoft.Win32;

class Sample 
{
//-------------------------------------------------------------------------------------
// Globals: 
//-------------------------------------------------------------------------------------
    protected static string fmtNameValue = "  {0} {1}.";
    protected static string myVarSuffix = "_GETSET_ENVAR_SAMPLE";

// Four relatively unique environment variable names.
    protected static string myVarA = "A" + myVarSuffix; // default process
    protected static string myVarB = "B" + myVarSuffix; // Current Process
    protected static string myVarC = "C" + myVarSuffix; // Current User
    protected static string myVarD = "D" + myVarSuffix; // Local Machine
//=====================================================================================
// EachVariable: 
// Test whether a specific environment variable exists in a target.
// This section demonstrates Environment.GetEnvironmentVariable.
//-------------------------------------------------------------------------------------
    protected static void EachVariable(string var, EnvironmentVariableTarget tgt)
    {
    string str;
    //
    if (0 == tgt)          // Zero means use the default target.
        str = Environment.GetEnvironmentVariable(var);
    else
        str = Environment.GetEnvironmentVariable(var, tgt);
    Console.WriteLine(fmtNameValue, 
                      var, (String.IsNullOrEmpty(str) ? "doesn't exist" : str));
    }
//-------------------------------------------------------------------------------------
// CheckEachVariable: 
// Uses EachVariable to test whether each environment variable exists in a target.
//-------------------------------------------------------------------------------------
    protected static void CheckEachVariable()
    {
    Console.WriteLine("Process:");
    EachVariable(myVarA, 0);  // Check the default target (current process)
    EachVariable(myVarB, EnvironmentVariableTarget.Process);
    EachVariable(myVarC, EnvironmentVariableTarget.Process);
    EachVariable(myVarD, EnvironmentVariableTarget.Process);
    Console.WriteLine();

    Console.WriteLine("User:");
    EachVariable(myVarA, EnvironmentVariableTarget.User);
    EachVariable(myVarB, EnvironmentVariableTarget.User);
    EachVariable(myVarC, EnvironmentVariableTarget.User);
    EachVariable(myVarD, EnvironmentVariableTarget.User);
    Console.WriteLine();

    Console.WriteLine("Machine:");
    EachVariable(myVarA, EnvironmentVariableTarget.Machine);
    EachVariable(myVarB, EnvironmentVariableTarget.Machine);
    EachVariable(myVarC, EnvironmentVariableTarget.Machine);
    EachVariable(myVarD, EnvironmentVariableTarget.Machine);
    Console.WriteLine();
    }
//=====================================================================================
// AllVariables: CheckAllVariables helper function.
// This section demonstrates Environment.GetEnvironmentVariables.
//-------------------------------------------------------------------------------------
    private static void AllVariables(EnvironmentVariableTarget tgt)
    {
    string value;
    string key;

    foreach(DictionaryEntry de in Environment.GetEnvironmentVariables(tgt))
        {
        key   = (string)de.Key;
        value = (string)de.Value;
        if (key.Contains(myVarSuffix))
            Console.WriteLine(fmtNameValue, key, value);
        }
    Console.WriteLine();
    }
//=====================================================================================
// CheckAllVariables: 
// Uses AllVariables to test whether each environment variable exists in a target.
//-------------------------------------------------------------------------------------
    protected static void CheckAllVariables()
    {
    Console.WriteLine("Process:");
    AllVariables(EnvironmentVariableTarget.Process);

    Console.WriteLine("User:");
    AllVariables(EnvironmentVariableTarget.User);

    Console.WriteLine("Machine:");
    AllVariables(EnvironmentVariableTarget.Machine);
    }
//=====================================================================================
// ChkReg: CheckRegistry helper function.
// This function filters out irrelevant environment variables. 
//-------------------------------------------------------------------------------------
    private static void ChkReg(RegistryKey rk)
    {
    bool exists = false;
    string registryNone = "  Environment variable doesn't exist.";

    foreach (string s in rk.GetValueNames())
        {
        if (s.Contains(myVarSuffix))
            {
            Console.WriteLine(fmtNameValue, s, (string)rk.GetValue(s));
            exists = true;
            }
        }
    if (exists == false)
        Console.WriteLine(registryNone);
    Console.WriteLine();
    }
//-------------------------------------------------------------------------------------
// CheckRegistry: 
// Uses ChkReg to display the User and Machine environment variables in the registry.
//-------------------------------------------------------------------------------------
    protected static void CheckRegistry()
    {
    string subkeyU = @"Environment";
    string subkeyM = @"System\CurrentControlSet\Control\Session Manager\Environment";
    string fmtSubkey = "\"{0}\" key:";

    Console.WriteLine(fmtSubkey, subkeyU);
    ChkReg(Registry.CurrentUser.OpenSubKey(subkeyU));

    Console.WriteLine(fmtSubkey, subkeyM);
    ChkReg(Registry.LocalMachine.OpenSubKey(subkeyM));
    }
//=====================================================================================
// Main:
//-------------------------------------------------------------------------------------
    public static void Main() 
    {
//-------------------------------------------------------------------------------------
// Environment variable values
//-------------------------------------------------------------------------------------
    string existsA = "exists in the default target (Process)";
    string existsB = "exists in Process";
    string existsC = "exists in User";
    string existsD = "exists in Machine";
//-------------------------------------------------------------------------------------
// Messages:
//-------------------------------------------------------------------------------------
    string msg1  = "Step 1:\n" +
                       "  Check whether the environment variables already exist in \n" + 
                       "  the various targets...\n";
    string msg2  = "Step 2:\n" +
                       "  Set the environment variable for each target...\n";
    string msg31 = "Step 3, part 1:\n" + 
                       "  Display the environment variables in each target...\n";
    string msg32 = "Step 3, part 2:\n" +
                       "  Check whether the User and Machine environment variables \n" +
                       "  were created in the Windows operating system registry...\n";
    string msg41 = "Step 4, part 1:\n" +
                       "  Delete the environment variables created for this sample...\n";
    string msg42 = "Step 4, part 2:\n" +
                       "  Check whether the environment variables were deleted \n" +
                       "  in each target...\n";
    string msg43 = "Step 4, part 3:\n" + 
                       "  Check whether the User and Machine environment variables \n" +
                       "  were deleted from the Windows operating system registry...\n";
    string fmt2x   = "  {0,9}: Set {1} = \"{2}\"";
//-------------------------------------------------------------------------------------
// Step 1:
// Check whether the sample environment variables already exist.
// WARNING: These variables will be deleted at the end of this sample.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg1);
    CheckEachVariable();
    Console.WriteLine();
//-------------------------------------------------------------------------------------
// Step 2:
// Set the environment variable for each target.
// This section demonstrates Environment.SetEnvironmentVariable.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg2);
// Set the environment variable for the default target (the current process).
    Console.WriteLine(fmt2x, "(default)", myVarA, existsA);
    Environment.SetEnvironmentVariable(myVarA, existsA);

// Set the environment variable for the the current process.
    Console.WriteLine(fmt2x, "Process", myVarB, existsB);
    Environment.SetEnvironmentVariable(myVarB, existsB, 
        EnvironmentVariableTarget.Process);

// Set the environment variable for the the current user.
    Console.WriteLine(fmt2x, "User", myVarC, existsC);
    Environment.SetEnvironmentVariable(myVarC, existsC, 
        EnvironmentVariableTarget.User);

// Set the environment variable for the the local machine.
    Console.WriteLine(fmt2x, "Machine", myVarD, existsD);
    Environment.SetEnvironmentVariable(myVarD, existsD, 
        EnvironmentVariableTarget.Machine);
    Console.WriteLine();
//-------------------------------------------------------------------------------------
// Step 3, part 1:
// Display the environment variables in each target.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg31);
    CheckAllVariables();
    Console.WriteLine();
//-------------------------------------------------------------------------------------
// Step 3, part 2:
// Check whether the User and Machine environment variables were created in the Windows 
// operating system registry.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg32);
    CheckRegistry();
    Console.WriteLine();
//-------------------------------------------------------------------------------------
// Step 4, part 1:
// Delete the environment variables created for this sample.
// This section demonstrates using Environment.SetEnvironmentVariable to delete an 
// environment variable.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg41);
    Environment.SetEnvironmentVariable(myVarA, null);
    Environment.SetEnvironmentVariable(myVarB, null, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable(myVarC, null, EnvironmentVariableTarget.User);
    Environment.SetEnvironmentVariable(myVarD, null, EnvironmentVariableTarget.Machine);
//-------------------------------------------------------------------------------------
// Step 4, part 2:
// Check whether the environment variables were deleted in each target.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg42);
    CheckEachVariable();
//-------------------------------------------------------------------------------------
// Step 4, part 3:
// Check whether the User and Machine environment variables were deleted from the 
// Windows operating system registry.
//-------------------------------------------------------------------------------------
    Console.WriteLine(msg43);
    CheckRegistry();
    }
}
/*
This example produces the following results:

Step 1:
  Check whether the environment variables already exist in
  the various targets...

Process:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.

User:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.

Machine:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.


Step 2:
  Set the environment variable for each target...

  (default): Set A_GETSET_ENVAR_SAMPLE = "exists in the default target (Process)"
    Process: Set B_GETSET_ENVAR_SAMPLE = "exists in Process"
       User: Set C_GETSET_ENVAR_SAMPLE = "exists in User"
    Machine: Set D_GETSET_ENVAR_SAMPLE = "exists in Machine"

Step 3, part 1:
  Display the environment variables in each target...

Process:
  B_GETSET_ENVAR_SAMPLE exists in Process.
  A_GETSET_ENVAR_SAMPLE exists in the default target (Process).

User:
  C_GETSET_ENVAR_SAMPLE exists in User.

Machine:
  D_GETSET_ENVAR_SAMPLE exists in Machine.


Step 3, part 2:
  Check whether the User and Machine environment variables
  were created in the Windows operating system registry...

"Environment" key:
  C_GETSET_ENVAR_SAMPLE exists in User.

"System\CurrentControlSet\Control\Session Manager\Environment" key:
  D_GETSET_ENVAR_SAMPLE exists in Machine.


Step 4, part 1:
  Delete the environment variables created for this sample...

Step 4, part 2:
  Check whether the environment variables were deleted
  in each target...

Process:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.

User:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.

Machine:
  A_GETSET_ENVAR_SAMPLE doesn't exist.
  B_GETSET_ENVAR_SAMPLE doesn't exist.
  C_GETSET_ENVAR_SAMPLE doesn't exist.
  D_GETSET_ENVAR_SAMPLE doesn't exist.

Step 4, part 3:
  Check whether the User and Machine environment variables
  were deleted from the Windows operating system registry...

"Environment" key:
  Environment variable doesn't exist.

"System\CurrentControlSet\Control\Session Manager\Environment" key:
  Environment variable doesn't exist.
*/

异常

异常 异常描述
ArgumentNullException variable 为 null。
ArgumentException
  • variable 包含零长度字符串、起始十六进制零字符 (0x00) 或等号(“=”)。
  • variable 的长度大于等于 32,767 个字符。
  • target 不是 EnvironmentVariableTarget 枚举的成员。
  • target 为 Machine 或 User,并且 variable 的长度大于等于 255。
  • target 为 Process,并且 value 的长度大于等于 32,767 个字符。
  • 在执行此操作的过程中发生错误。
NotSupportedException target 是 User 或 Machine,当前操作系统为 Windows 95、Windows 98 或 Windows Me。
SecurityException 调用方不具有执行此操作所需的权限。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。