Environment.SetEnvironmentVariable Environment.SetEnvironmentVariable Environment.SetEnvironmentVariable Environment.SetEnvironmentVariable Method

定义

创建、修改或删除环境变量。Creates, modifies, or deletes an environment variable.

重载

SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String)

创建、修改或删除当前进程中存储的环境变量。Creates, modifies, or deletes an environment variable stored in the current process.

SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

创建、修改或删除当前进程中或者为当前用户或本地计算机保留的 Windows 操作系统注册表项中存储的环境变量。Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.

SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String) SetEnvironmentVariable(String, String)

创建、修改或删除当前进程中存储的环境变量。Creates, modifies, or deletes an environment variable stored in the current process.

public:
 static void SetEnvironmentVariable(System::String ^ variable, System::String ^ value);
public static void SetEnvironmentVariable (string variable, string value);
static member SetEnvironmentVariable : string * string -> unit
Public Shared Sub SetEnvironmentVariable (variable As String, value As String)

参数

variable
String String String String

环境变量名。The name of an environment variable.

value
String String String String

要分配给 variable 的值。A value to assign to variable.

异常

variable 包含一个长度为零的字符串、一个初始十六进制零字符 (0x00) 或一个等号 ("=")。variable contains a zero-length string, an initial hexadecimal zero character (0x00), or an equal sign ("=").

-or- variablevalue 的长度大于或等于 32,767 个字符。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.

调用方没有执行此操作所需的权限。The caller does not have the required permission to perform this operation.

示例

下面的示例尝试从进程环境块中检索名为Test1的环境变量的值。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. 对于在 Windows 系统上运行的 .net 实现,它还GetEnvironmentVariables(EnvironmentVariableTarget)将调用方法和EnvironmentVariableTarget枚举的每个成员,以确定只能从当前进程环境块检索变量。For .NET implementations running on Windows systems, 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. (基于 Unix 的系统上的 .NET 实现仅支持进程环境块中的变量。)最后,如果该示例创建了变量,则将其删除。(.NET implementations on Unix-based systems only support variables in the 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: {value}\n");
      
      // Confirm that the value can only be retrieved from the process
      // environment block if running on a Windows system.
      if (Environment.OSVersion.Platform == PlatformID.Win32NT) 
      {
         Console.WriteLine("Attempting to retrieve Test1 from:");
         foreach (EnvironmentVariableTarget enumValue in 
                           Enum.GetValues(typeof(EnvironmentVariableTarget))) {
            value = Environment.GetEnvironmentVariable("Test1", enumValue);
            Console.WriteLine($"   {enumValue}: {(value != null ? "found" : "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 if run on a Windows system:
//      Test1: Value1
//
//      Attempting to retrieve Test1 from:
//         Process: found
//         User: not found
//         Machine: not found
//
//      Test1 has been deleted.
//
// The example displays the following output if run on a Unix-based system:
//      Test1: Value1
//
//      Test1 has been deleted.
Module Example
   Public Sub Main()
      Dim value As String 
      Dim toDelete As Boolean = False
      
      ' Check whether the environment variable exists.
      value = Environment.GetEnvironmentVariable("Test1")
      ' If necessary, create it.
      If value Is Nothing Then
         Environment.SetEnvironmentVariable("Test1", "Value1")
         toDelete = True
         
         ' Now retrieve it.
         value = Environment.GetEnvironmentVariable("Test1")
      End If
      ' Display the value.
      Console.WriteLine($"Test1: {value}")
      Console.WriteLine()
      
      ' Confirm that the value can only be retrieved from the process
      ' environment block if running on a Windows system.
      If Environment.OSVersion.Platform = PlatformID.Win32NT Then
         Console.WriteLine("Attempting to retrieve Test1 from:")
         For Each enumValue As EnvironmentVariableTarget In 
                           [Enum].GetValues(GetType(EnvironmentVariableTarget))
            value = Environment.GetEnvironmentVariable("Test1", enumValue)
            Console.WriteLine($"   {enumValue}: {If(value IsNot Nothing, "found", "not found")}")
         Next
         Console.WriteLine()
      End If

      ' If we've created it, now delete it.
      If toDelete Then 
         Environment.SetEnvironmentVariable("Test1", Nothing)
         ' Confirm the deletion.
         If Environment.GetEnvironmentVariable("Test1") = Nothing Then
            Console.WriteLine("Test1 has been deleted.")
         End If
      End If         
   End Sub
End Module
' The example displays the following output if run on a Windows system:
'      Test1: Value1
'
'      Attempting to retrieve Test1 from:
'         Process: found
'         User: not found
'         Machine: not found
'
'      Test1 has been deleted.
'
' The example displays the following output if run on a Unix-based system:
'      Test1: Value1
'
'      Test1 has been deleted.

注解

调用此方法等效于使用SetEnvironmentVariable(String, String, EnvironmentVariableTarget) target参数的EnvironmentVariableTarget.Process值调用重载。Calling this method is equivalent to calling the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) overload with a value of EnvironmentVariableTarget.Process for the target argument.

如果参数不为空(请参阅本部分稍后部分中针对空值的定义删除环境变量),并且variable参数命名的环境变量不存在,环境value创建变量,并为其分配内容valueIf 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.

如果variable包含非初始的十六进制零字符,则在零字符之前的字符被视为环境变量名称,而所有后续字符都将被忽略。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.

如果value包含非初始的十六进制零字符,则零字符之前的字符将被分配给环境变量,并且所有后续字符都将被忽略。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.

如果value为空且名为的variable环境变量存在,则将删除环境变量。If value is empty and the environment variable named by variable exists, the environment variable is deleted. 如果variable不存在,即使无法执行该操作,也不会发生错误。If variable does not exist, no error occurs even though the operation cannot be performed. value在下列任一情况下,都被视为空:value is considered empty under any of the following conditions:

  • 它是nullIt is null.

  • 它是String.EmptyIt is String.Empty.

  • 它包含值为 U + 0000 的单个字符。It consists of a single character whose value is U+0000.

安全性

EnvironmentPermission
用于完全访问环境变量。for full access to environment variables. 关联的枚举:UnrestrictedAssociated enumeration: Unrestricted

另请参阅

SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget) SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

创建、修改或删除当前进程中或者为当前用户或本地计算机保留的 Windows 操作系统注册表项中存储的环境变量。Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.

public:
 static void SetEnvironmentVariable(System::String ^ variable, System::String ^ value, EnvironmentVariableTarget target);
public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target);
static member SetEnvironmentVariable : string * string * EnvironmentVariableTarget -> unit
Public Shared Sub SetEnvironmentVariable (variable As String, value As String, target As EnvironmentVariableTarget)

参数

variable
String String String String

环境变量名。The name of an environment variable.

value
String String String String

要分配给 variable 的值。A value to assign to variable.

target
EnvironmentVariableTarget EnvironmentVariableTarget EnvironmentVariableTarget EnvironmentVariableTarget

一个用于指定环境变量的位置的枚举值。One of the enumeration values that specifies the location of the environment variable.

异常

variable 包含一个长度为零的字符串、一个初始十六进制零字符 (0x00) 或一个等号 ("=")。variable contains a zero-length string, an initial hexadecimal zero character (0x00), or an equal sign ("=").

- 或 --or- variable 的长度大于或等于 32,767 个字符。The length of variable is greater than or equal to 32,767 characters.

- 或 --or- target 不是 EnvironmentVariableTarget 枚举的一个成员。target is not a member of the EnvironmentVariableTarget enumeration.

-or- targetMachineUser,且 variable 的长度大于或等于 255。target is Machine or User, and the length of variable is greater than or equal to 255.

-or- targetProcess ,且 value 的长度大于或等于 32767 个字符。target is Process and the length of value is greater than or equal to 32,767 characters.

-or- 执行此操作期间出错。An error occurred during the execution of this operation.

调用方没有执行此操作所需的权限。The caller does not have the required permission to perform this operation.

示例

下面的示例为EnvironmentVariableTarget.ProcessEnvironmentVariableTarget.UserMachine目标创建环境变量,检查操作系统注册表是否包含用户和计算机环境变量,然后删除环境变化.The following example creates environment variables for the EnvironmentVariableTarget.Process, EnvironmentVariableTarget.User, and Machine targets, checks whether the operating system registry contains the user and machine environment variables, then deletes the environment variables. 由于基于 Unix 的系统上的 .net 不支持每用户和每台计算机的环境变量,因此SetEnvironmentVariable(String, String)只有SetEnvironmentVariable(String, String, EnvironmentVariableTarget)和值EnvironmentVariableTarget.Process才能成功地将环境变量存储到进程环境块。Because .NET on Unix-based systems does not support per-user and per-machine environment variables, only SetEnvironmentVariable(String, String) and SetEnvironmentVariable(String, String, EnvironmentVariableTarget) with a value of EnvironmentVariableTarget.Process successfully store an environment variable to the process environment block.

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

class Sample 
{
    public static void Main() 
    {
        // Environment variable names for default, process, user, and machine targets.
        string defaultEnvVar = nameof(defaultEnvVar);
        string processEnvVar = nameof(processEnvVar);
        string userEnvVar = nameof(userEnvVar);
        string machineEnvVar = nameof(machineEnvVar);

        string dft = nameof(dft);
        string process = nameof(process);
        string user = nameof(user);
        string machine = nameof(machine);

        // Set the environment variable for each target.
        Console.WriteLine("Setting environment variables for each target...\n");
        // The default target (the current process).
        Environment.SetEnvironmentVariable(defaultEnvVar, dft);
        // The current process.
        Environment.SetEnvironmentVariable(processEnvVar, process, 
                                           EnvironmentVariableTarget.Process);
        // The current user.
        Environment.SetEnvironmentVariable(userEnvVar, user, 
                                           EnvironmentVariableTarget.User);
        // The local machine.
        Environment.SetEnvironmentVariable(machineEnvVar, machine, 
                                           EnvironmentVariableTarget.Machine);

        // Define an array of environment variables.
        string[] envVars = { defaultEnvVar,processEnvVar, userEnvVar, machineEnvVar };
        
        // Try to get the environment variables from each target.
        // The default (no specified target).
        Console.WriteLine("Retrieving environment variables from the default target:");
        foreach (var envVar in envVars)
        {
          var value = Environment.GetEnvironmentVariable(envVar) ?? "(none)";
          Console.WriteLine($"   {envVar}: {value}");
        }
        // The process block.
        Console.WriteLine("\nRetrieving environment variables from the Process target:");
        foreach (var envVar in envVars)
        {
          var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process) ?? "(none)";
          Console.WriteLine($"   {envVar}: {value}");
        }
        // The user block.
        Console.WriteLine("\nRetrieving environment variables from the User target:");
        foreach (var envVar in envVars)
        {
          var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User) ?? "(none)";
          Console.WriteLine($"   {envVar}: {value}");
        }
        // The machine block.
        Console.WriteLine("\nRetrieving environment variables from the Machine target:");
        foreach (var envVar in envVars)
        {
          var value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Machine) ?? "(none)";
          Console.WriteLine($"   {envVar}: {value}");
        }

        // Delete the environment variable for each target.
        Console.WriteLine("\nDeleting environment variables for each target...\n");
        // The default target (the current process).
        Environment.SetEnvironmentVariable(defaultEnvVar, null);
        // The current process.
        Environment.SetEnvironmentVariable(processEnvVar, null, 
                                           EnvironmentVariableTarget.Process);
        // The current user.
        Environment.SetEnvironmentVariable(userEnvVar, null, 
                                           EnvironmentVariableTarget.User);
        // The local machine.
        Environment.SetEnvironmentVariable(machineEnvVar, null, 
                                           EnvironmentVariableTarget.Machine);
    }
}
// The example displays the following output if run on a Windows system:
//      Setting environment variables for each target...
//
//      Retrieving environment variables from the default target:
//        defaultEnvVar: dft
//        processEnvVar: process
//        userEnvVar: user
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the Process target:
//        defaultEnvVar: dft
//        processEnvVar: process
//        userEnvVar: user
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the User target:
//        defaultEnvVar: (none)
//        processEnvVar: (none)
//        userEnvVar: user
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the Machine target:
//        defaultEnvVar: (none)
//        processEnvVar: (none)
//        userEnvVar: (none)
//        machineEnvVar: machine
//
//      Deleting environment variables for each target...
//
// The example displays the following output if run on a Unix-based system:
//
//      Setting environment variables for each target...
//
//      Retrieving environment variables from the default target:
//        defaultEnvVar: dft
//        processEnvVar: process
//        userEnvVar: (none)
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the Process target:
//        defaultEnvVar: dft
//        processEnvVar: process
//        userEnvVar: (none)
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the User target:
//        defaultEnvVar: (none)
//        processEnvVar: (none)
//        userEnvVar: (none)
//        machineEnvVar: (none)
//
//      Retrieving environment variables from the Machine target:
//        defaultEnvVar: (none)
//        processEnvVar: (none)
//        userEnvVar: (none)
//        machineEnvVar: (none)
//
//      Deleting environment variables for each target...
Imports System.Collections
Imports Microsoft.Win32

Module Sample 
    Public Sub Main() 
        ' Environment variable names for default, process, user, and machine targets.
        Dim defaultEnvVar As String = NameOf(defaultEnvVar)
        Dim processEnvVar As String = NameOf(processEnvVar)
        Dim userEnvVar As String = NameOf(userEnvVar)
        Dim machineEnvVar As String = NameOf(machineEnvVar)

        Dim dft As String = NameOf(dft)
        Dim process As String = NameOf(process)
        Dim user As String = NameOf(user)
        Dim machine As String = NameOf(machine)

        ' Set the environment variable for each target.
        Console.WriteLine("Setting environment variables for each target...")
        ' The default target (the current process).
        Environment.SetEnvironmentVariable(defaultEnvVar, dft)
        ' The current process.
        Environment.SetEnvironmentVariable(processEnvVar, process, 
                                           EnvironmentVariableTarget.Process)
        ' The current user.
        Environment.SetEnvironmentVariable(userEnvVar, user, 
                                           EnvironmentVariableTarget.User)
        ' The local machine.
        Environment.SetEnvironmentVariable(machineEnvVar, machine, 
                                           EnvironmentVariableTarget.Machine)
        Console.WriteLine()

        ' Define an array of environment variables.
        Dim envVars As String() = { defaultEnvVar, processEnvVar, userEnvVar, machineEnvVar }
        
        ' Try to get the environment variables from each target.
        ' The default (no specified target).
        Console.WriteLine("Retrieving environment variables from the default target:")
        For Each envVar in envVars
          Dim value = Environment.GetEnvironmentVariable(envVar)
          Console.WriteLine($"   {envVar}: {If(value IsNot Nothing, value, "(none)")}")
        Next
        Console.WriteLine()
        ' The process block.
        Console.WriteLine("Retrieving environment variables from the Process target:")
        For Each envVar in envVars
          Dim value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process)
          Console.WriteLine($"   {envVar}: {If(value IsNot Nothing, value, "(none)")}")
        Next
        Console.WriteLine()
        ' The user block.
        Console.WriteLine("Retrieving environment variables from the User target:")
        For Each envVar in envVars
          Dim value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User)
          Console.WriteLine($"   {envVar}: {value}")
        Next
        Console.WriteLine()
        ' The machine block.
        Console.WriteLine("Retrieving environment variables from the Machine target:")
        For Each envVar in envVars
          Dim value = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Machine)
          Console.WriteLine($"   {envVar}: {value}")
        Next
        Console.WriteLine()

        ' Delete the environment variable for each target.
        Console.WriteLine("Deleting environment variables for each target...")
        ' The default target (the current process).
        Environment.SetEnvironmentVariable(defaultEnvVar, Nothing)
        ' The current process.
        Environment.SetEnvironmentVariable(processEnvVar, Nothing, 
                                           EnvironmentVariableTarget.Process)
        ' The current user.
        Environment.SetEnvironmentVariable(userEnvVar, Nothing, 
                                           EnvironmentVariableTarget.User)
        ' The local machine.
        Environment.SetEnvironmentVariable(machineEnvVar, Nothing, 
                                           EnvironmentVariableTarget.Machine)
    End Sub
End Module
' The example displays the following output if run on a Windows system:
'      Setting environment variables for each target...
'
'      Retrieving environment variables from the default target:
'        defaultEnvVar: dft
'        processEnvVar: process
'        userEnvVar: user
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the Process target:
'        defaultEnvVar: dft
'        processEnvVar: process
'        userEnvVar: user
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the User target:
'        defaultEnvVar: (none)
'        processEnvVar: (none)
'        userEnvVar: user
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the Machine target:
'        defaultEnvVar: (none)
'        processEnvVar: (none)
'        userEnvVar: (none)
'        machineEnvVar: machine
'
'      Deleting environment variables for each target...
'
' The example displays the following output if run on a Unix-based system:
'
'      Setting environment variables for each target...
'
'      Retrieving environment variables from the default target:
'        defaultEnvVar: dft
'        processEnvVar: process
'        userEnvVar: (none)
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the Process target:
'        defaultEnvVar: dft
'        processEnvVar: process
'        userEnvVar: (none)
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the User target:
'        defaultEnvVar: (none)
'        processEnvVar: (none)
'        userEnvVar: (none)
'        machineEnvVar: (none)
'
'      Retrieving environment variables from the Machine target:
'        defaultEnvVar: (none)
'        processEnvVar: (none)
'        userEnvVar: (none)
'        machineEnvVar: (none)
'
'      Deleting environment variables for each target...

注解

方法允许您定义可用于当前进程的环境变量Process (值)。 SetEnvironmentVariable(String, String, EnvironmentVariableTarget)The SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method lets you define an environment variable that is available to the current process (the Process value). 当前进程环境块独有的环境变量仅在进程结束之前持久存在。Environment variables that are unique to the current process environment block persist only until the process ends.

此外,在 Windows 系统SetEnvironmentVariable(String, String, EnvironmentVariableTarget)上,方法允许您定义一个环境变量,该变量可用于在计算机上运行的所有进程EnvironmentVariableTarget.Machine (值)以及用户运行的所有进程( EnvironmentVariableTarget.User值)。In addition, on Windows systems only, the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method lets you define an environment variable that is available to all processes that run on a machine (the EnvironmentVariableTarget.Machine value) and to all processes run by a user (the EnvironmentVariableTarget.User value). 每计算机和每用户环境变量将复制到当前进程的环境块中。Per-machine and per-user environment variables are copied into the environment block of the current process.

在 macOS 和 Linux 系统上的 .net Core 中,将SetEnvironmentVariable(String, String, EnvironmentVariableTarget)忽略EnvironmentVariableTarget.Machine值为或EnvironmentVariableTarget.User的对方法的调用。On .NET Core on macOS and Linux systems, calls to the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a value of EnvironmentVariableTarget.Machine or EnvironmentVariableTarget.User are ignored.

如果参数不为空(请参阅本部分稍后部分中针对空值的定义删除环境变量),并且variable参数命名的环境变量不存在,环境value创建变量,并为其分配内容valueIf 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 argument does not exist, the environment variable is created and assigned the contents of value. 如果它存在,则修改其值。If it does exist, its value is modified.

如果variable包含非初始的十六进制零字符,则在零字符之前的字符被视为环境变量名称,而所有后续字符都将被忽略。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.

如果value包含非初始的十六进制零字符,则零字符之前的字符将被分配给环境变量,并且所有后续字符都将被忽略。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.

如果value为空且名为的variable环境变量存在,则将删除环境变量。If value is empty and the environment variable named by variable exists, the environment variable is deleted. value在下列任一情况下,都被视为空:value is considered empty under any of the following conditions:

  • 它是nullIt is null.

  • 它是String.EmptyIt is String.Empty.

  • 它包含值为 U + 0000 的单个字符。It consists of a single character whose value is U+0000.

如果variable不存在,则不会发生任何错误,但无法执行该操作。If variable does not exist, no error occurs although the operation cannot be performed. 当是target Machine时,请小心,因为你可能会意外删除影响整个本地计算机的环境变量,而不只是当前进程或用户。Be careful when target is Machine, because you can accidentally delete an environment variable that affects your entire local machine, not just the current process or user.

Windows 系统上的 EnvironmentVariableTarget 和 EnvironmentVariableTargetEnvironmentVariableTarget.Machine and EnvironmentVariableTarget.User on Windows systems

如果targetEnvironmentVariableTarget.User,则将环境变量存储在本地计算机注册表的 HKEY_CURRENT_USER\Environment 项中。If target is EnvironmentVariableTarget.User, the environment variable is stored in the HKEY_CURRENT_USER\Environment key of the local computer's registry. 它还会复制到以当前用户身份运行的文件资源管理器实例。It is also copied to instances of File Explorer that are running as the current user. 然后,用户从文件资源管理器启动的任何新进程都将继承该环境变量。The environment variable is then inherited by any new processes that the user launches from File Explorer.

同样,如果targetEnvironmentVariableTarget.Machine,则将环境变量存储在本地计算机注册表的 HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment 键中。Similarly, if target is EnvironmentVariableTarget.Machine, the environment variable is stored in the HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment key of the local computer's registry. 它还会复制到文件资源管理器的所有实例。It is also copied to all instances of File Explorer. 然后,环境变量由从文件资源管理器启动的任何新进程继承。The environment variable is then inherited by any new processes that are launched from File Explorer.

如果targetUser WM_SETTINGCHANGE或,Machine则由 Windows 消息通知其他应用程序的设置操作。If target is User or Machine, other applications are notified of the set operation by a Windows WM_SETTINGCHANGE message.

如果targetEnvironmentVariableTarget.User value或,EnvironmentVariableTarget.Machine则建议长度小于2048个字符。If target is EnvironmentVariableTarget.User or EnvironmentVariableTarget.Machine, we recommend that the length of value be less than 2048 characters.

安全性

EnvironmentPermission
用于完全访问环境变量。for full access to environment variables. 关联的枚举:UnrestrictedAssociated enumeration: Unrestricted

另请参阅

适用于