Environment.SetEnvironmentVariable Metoda

Definicja

Tworzy, modyfikuje lub usuwa zmienną środowiskową.

Przeciążenia

SetEnvironmentVariable(String, String)

Tworzy, modyfikuje lub usuwa zmienną środowiskową przechowywaną w bieżącym procesie.

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

Tworzy, modyfikuje lub usuwa zmienną środowiskową przechowywaną w bieżącym procesie lub w kluczu rejestru systemu operacyjnego Windows zarezerwowanym dla bieżącego użytkownika lub komputera lokalnego.

SetEnvironmentVariable(String, String)

Źródło:
Environment.cs
Źródło:
Environment.cs
Źródło:
Environment.cs

Tworzy, modyfikuje lub usuwa zmienną środowiskową przechowywaną w bieżącym procesie.

public:
 static void SetEnvironmentVariable(System::String ^ variable, System::String ^ value);
public static void SetEnvironmentVariable (string variable, 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)

Parametry

variable
String

Nazwa zmiennej środowiskowej.

value
String

Wartość, która ma zostać przypisana do variableelementu .

Wyjątki

variable to null.

variable zawiera ciąg o zerowej długości, początkowy znak szesnastkowy (0x00) lub znak równości ("=").

-lub-

Długość variable znaków lub value jest większa lub równa 32 767 znaków.

-lub-

Wystąpił błąd podczas wykonywania tej operacji.

Obiekt wywołujący nie ma wymaganych uprawnień do wykonania tej operacji.

Przykłady

Poniższy przykład próbuje pobrać wartość zmiennej środowiskowej o nazwie Test1 z bloku środowiska procesu. Jeśli zmienna nie istnieje, przykład tworzy zmienną i pobiera jej wartość. W przykładzie jest wyświetlana wartość zmiennej. W przypadku implementacji platformy .NET uruchomionych w systemach Windows wywołuje również metodę GetEnvironmentVariables(EnvironmentVariableTarget) z każdym elementem EnvironmentVariableTarget członkowskim wyliczenia, aby ustalić, że zmienna może być pobierana tylko z bieżącego bloku środowiska procesu. (Implementacje platformy .NET w systemach podobnych do unix obsługują tylko zmienne w bloku środowiska procesu). Na koniec, jeśli przykład utworzył zmienną, usuwa ją.

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

open System

let mutable toDelete = false

// Check whether the environment variable exists.
let value = 
    let v = Environment.GetEnvironmentVariable "Test1"
    // If necessary, create it.
    if isNull v then
        Environment.SetEnvironmentVariable("Test1", "Value1")
        toDelete <- true
        Environment.GetEnvironmentVariable "Test1"
    else 
        v

// Display the value.
printfn $"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 then
    printfn "Attempting to retrieve Test1 from:"
    for enumValue in Enum.GetValues typeof<EnvironmentVariableTarget> do
        let value = Environment.GetEnvironmentVariable("Test1", enumValue :?> EnvironmentVariableTarget)
        printfn $"""   {enumValue}: {if value <> null then "found" else "not found"}"""
    printfn ""

// If we've created it, now delete it.
if toDelete then
    Environment.SetEnvironmentVariable("Test1", null)
    // Confirm the deletion.
    if Environment.GetEnvironmentVariable "Test1" |> isNull then
        printfn "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.

Uwagi

Wywołanie tej metody jest równoważne wywołaniu SetEnvironmentVariable(String, String, EnvironmentVariableTarget) przeciążenia z wartością EnvironmentVariableTarget.Process dla argumentu target .

W systemach przypominających system Unix wywołania SetEnvironmentVariable(String, String) metody nie mają wpływu na biblioteki natywne, które są lub zostaną załadowane. (Z drugiej strony modyfikacje środowiska przetwarzania wprowadzone przez biblioteki natywne nie są widoczne przez zarządzane obiekty wywołujące).

value Jeśli argument nie jest pusty (zobacz omówienie usuwania zmiennej środowiskowej w dalszej części tej sekcji, aby uzyskać definicję pustej wartości) i zmienna środowiskowa o nazwie przez variable parametr nie istnieje, zmienna środowiskowa jest tworzona i przypisywana zawartość value. Jeśli istnieje, jego wartość zostanie zmodyfikowana. Ponieważ zmienna środowiskowa jest definiowana w bloku środowiskowym tylko bieżącego procesu, nie jest ona utrwalana po zakończeniu procesu.

Jeśli variable zawiera inicjalny znak szesnastkowy, znaki przed znakiem zerowym są traktowane jako nazwa zmiennej środowiskowej, a wszystkie kolejne znaki są ignorowane.

Jeśli value zawiera inicjalny znak szesnastkowy, znaki przed znakiem zerowym są przypisywane do zmiennej środowiskowej, a wszystkie kolejne znaki są ignorowane.

Jeśli value wartość jest pusta, a zmienna środowiskowa o nazwie variable by istnieje, zmienna środowiskowa zostanie usunięta. Jeśli variable nie istnieje, nie wystąpi błąd, mimo że nie można wykonać operacji. value jest uznawany za pusty w ramach dowolnego z następujących warunków:

  • Jest to null.
  • Jest to String.Empty.
  • Składa się z pojedynczego znaku, którego wartość to U+0000.

Zobacz też

Dotyczy

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

Źródło:
Environment.cs
Źródło:
Environment.cs
Źródło:
Environment.cs

Tworzy, modyfikuje lub usuwa zmienną środowiskową przechowywaną w bieżącym procesie lub w kluczu rejestru systemu operacyjnego Windows zarezerwowanym dla bieżącego użytkownika lub komputera lokalnego.

public:
 static void SetEnvironmentVariable(System::String ^ variable, System::String ^ value, EnvironmentVariableTarget target);
public static void SetEnvironmentVariable (string variable, 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)

Parametry

variable
String

Nazwa zmiennej środowiskowej.

value
String

Wartość, która ma zostać przypisana do variableelementu .

target
EnvironmentVariableTarget

Jedna z wartości wyliczenia, która określa lokalizację zmiennej środowiskowej.

Wyjątki

variable to null.

variable zawiera ciąg o zerowej długości, początkowy znak szesnastkowy (0x00) lub znak równości ("=").

-lub-

Długość variable jest większa lub równa 32 767 znaków.

-lub-

target nie jest członkiem EnvironmentVariableTarget wyliczenia.

-lub-

target jest Machine lub User, a długość variable jest większa lub równa 255.

-lub-

targetjest i długość value jest Process większa lub równa 32 767 znaków.

-lub-

Wystąpił błąd podczas wykonywania tej operacji.

Obiekt wywołujący nie ma wymaganych uprawnień do wykonania tej operacji.

Przykłady

W poniższym przykładzie są tworzone zmienne środowiskowe dla EnvironmentVariableTarget.Processobiektów docelowych , EnvironmentVariableTarget.Useri Machine oraz sprawdza, czy rejestr systemu operacyjnego zawiera zmienne środowiskowe użytkownika i komputera, a następnie usuwa zmienne środowiskowe. Ponieważ platforma .NET w systemach podobnych do systemu Unix nie obsługuje zmiennych środowiskowych dla poszczególnych użytkowników i maszyn, tylko SetEnvironmentVariable(String, String) z SetEnvironmentVariable(String, String, EnvironmentVariableTarget) wartością pomyślnego EnvironmentVariableTarget.Process przechowywania zmiennej środowiskowej do bloku środowiska procesu.

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...
module Sample

open System

// Environment variable names for default, process, user, and machine targets.
let rec defaultEnvVar = nameof defaultEnvVar
let rec processEnvVar = nameof processEnvVar
let rec userEnvVar = nameof userEnvVar
let rec machineEnvVar = nameof machineEnvVar

let rec dft = nameof dft
let rec proc = nameof proc
let rec user = nameof user
let rec machine = nameof machine

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

// Define a list of environment variables.
let envVars = [ defaultEnvVar; processEnvVar; userEnvVar; machineEnvVar ]

// Try to get the environment variables from each target.
// The default (no specified target).
printfn "Retrieving environment variables from the default target:"
for envVar in envVars do
    let value = 
        match Environment.GetEnvironmentVariable envVar with
        | null -> "(none)"
        | v -> v
    printfn $"   {envVar}: {value}"

// The process block.
printfn "\nRetrieving environment variables from the Process target:"
for envVar in envVars do
    let value = 
        match Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process) with
        | null -> "(none)"
        | v -> v
    printfn $"   {envVar}: {value}"

// The user block.
printfn "\nRetrieving environment variables from the User target:"
for envVar in envVars do
    let value = 
        match Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User) with
        | null -> "(none)"
        | v -> v
    printfn $"   {envVar}: {value}"

// The machine block.
printfn "\nRetrieving environment variables from the Machine target:"
for envVar in envVars do
    let value = 
        match Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Machine) with
        | null -> "(none)"
        | v -> v
    printfn $"   {envVar}: {value}"

// Delete the environment variable for each target.
printfn "\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...

Uwagi

Metoda SetEnvironmentVariable(String, String, EnvironmentVariableTarget) umożliwia zdefiniowanie zmiennej środowiskowej dostępnej dla bieżącego procesu (wartości).Process Zmienne środowiskowe, które są unikatowe dla bieżącego bloku środowiska procesu, są utrwalane tylko do momentu zakończenia procesu.

Ponadto tylko w systemach Windows metoda umożliwia zdefiniowanie zmiennej środowiskowej dostępnej SetEnvironmentVariable(String, String, EnvironmentVariableTarget) dla wszystkich procesów uruchamianych na maszynie ( EnvironmentVariableTarget.Machine wartości) i wszystkich procesów uruchamianych przez użytkownika ( EnvironmentVariableTarget.User wartość). Zmienne środowiskowe na maszynę i użytkownika są kopiowane do bloku środowiskowego bieżącego procesu.

W systemach przypominających system Unix wywołania SetEnvironmentVariable(String, String, EnvironmentVariableTarget) metody z wartością EnvironmentVariableTarget.Machine lub EnvironmentVariableTarget.User są ignorowane.

W systemach przypominających system Unix wywołania SetEnvironmentVariable(String, String, EnvironmentVariableTarget) metody z wartością EnvironmentVariableTarget.Process nie mają wpływu na żadne biblioteki natywne, które są lub zostaną załadowane. (Z drugiej strony modyfikacje środowiska przetwarzania wprowadzone przez biblioteki natywne nie są widoczne przez zarządzane obiekty wywołujące).

value Jeśli argument nie jest pusty (zobacz dyskusję na temat usuwania zmiennej środowiskowej w dalszej części tej sekcji, aby uzyskać definicję pustej wartości), a zmienna środowiskowa nazwana przez variable argument nie istnieje, zmienna środowiskowa jest tworzona i przypisywana zawartość value. Jeśli istnieje, jego wartość zostanie zmodyfikowana.

Jeśli variable zawiera inicjalny znak szesnastkowy, znaki przed znakiem zerowym są traktowane jako nazwa zmiennej środowiskowej, a wszystkie kolejne znaki są ignorowane.

Jeśli value zawiera inicjalny znak szesnastkowy, znaki przed znakiem zerowym są przypisywane do zmiennej środowiskowej, a wszystkie kolejne znaki są ignorowane.

Jeśli value wartość jest pusta, a zmienna środowiskowa o nazwie variable by istnieje, zmienna środowiskowa zostanie usunięta. value jest uznawany za pusty w ramach dowolnego z następujących warunków:

  • Jest to null.
  • Jest to String.Empty.
  • Składa się z pojedynczego znaku, którego wartość to U+0000.

Jeśli variable nie istnieje, nie wystąpi błąd, chociaż nie można wykonać operacji. Należy zachować ostrożność, targetMachineponieważ można przypadkowo usunąć zmienną środowiskową, która ma wpływ na całą maszynę lokalną, a nie tylko bieżący proces lub użytkownika.

EnvironmentVariableTarget.Machine i EnvironmentVariableTarget.User w systemach Windows

Jeśli target jest EnvironmentVariableTarget.Userto , zmienna środowiskowa jest przechowywana w kluczu HKEY_CURRENT_USER\Environment rejestru komputera lokalnego. Jest on również kopiowany do wystąpień Eksplorator plików, które są uruchomione jako bieżący użytkownik. Zmienna środowiskowa jest następnie dziedziczona przez wszystkie nowe procesy uruchamiane przez użytkownika z Eksplorator plików.

Podobnie, jeśli target to EnvironmentVariableTarget.Machine, zmienna środowiskowa jest przechowywana w kluczu HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment rejestru komputera lokalnego. Jest on również kopiowany do wszystkich wystąpień Eksplorator plików. Zmienna środowiskowa jest następnie dziedziczona przez wszystkie nowe procesy uruchamiane z Eksplorator plików.

Jeśli target element to User lub Machine, inne aplikacje są powiadamiane o operacji ustawiania przez komunikat systemu Windows WM_SETTINGCHANGE .

Jeśli target parametr ma wartość EnvironmentVariableTarget.User lub EnvironmentVariableTarget.Machine, zalecamy, aby długość value znaków nie przekraczała 2048 znaków.

Zobacz też

Dotyczy