Environment.SetEnvironmentVariable メソッド

定義

環境変数を作成、変更、または削除します。

オーバーロード

SetEnvironmentVariable(String, String)

現在のプロセスに格納されている環境変数を作成、変更、または削除します。

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

現在のプロセス、または Windows オペレーティング システムのレジストリ キー (現在のユーザー用に予約されているレジストリ キーまたはローカル コンピューター用に予約されているレジストリ キー) に格納される環境変数を作成、変更、または削除します。

SetEnvironmentVariable(String, String)

現在のプロセスに格納されている環境変数を作成、変更、または削除します。

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)

パラメーター

variable
String

環境変数の名前。

value
String

variable に割り当てる値。

例外

variablenullです。

variable に、長さ 0 の文字列、最初の 16 進数 0 文字 (0x00)、または等号 ("=") が含まれています。

または

variable または value の長さが 32,767 文字以上です。

または

この操作の実行中にエラーが発生しました。

呼び出し元に、この操作を実行するために必要なアクセス許可がありません。

次の例では、プロセス環境ブロックから という名前 Test1 の環境変数の値の取得を試みます。 変数が存在しない場合、この例では 変数を作成し、その値を取得します。 この例では、 変数の値を表示します。 Windows システムで実行されている .NET 実装の場合は、 列挙体の各メンバーで メソッドを呼び出 GetEnvironmentVariables(EnvironmentVariableTarget) して、現在の EnvironmentVariableTarget プロセス環境ブロックからのみ変数を取得できることを確認します。 (Unix に似たシステムでの .NET 実装では、プロセス環境ブロック内の変数のみがサポートされます)。最後に、この例で変数を作成した場合は、変数を削除します。

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.

注釈

このメソッドの呼び出しは、 引数の値が のSetEnvironmentVariable(String, String, EnvironmentVariableTarget)EnvironmentVariableTarget.Processオーバーロードを呼び出すことtargetと同じです。

Unix に似たシステムでは、 メソッドの SetEnvironmentVariable(String, String) 呼び出しは、読み込まれるネイティブ ライブラリまたは読み込まれるネイティブ ライブラリには影響しません。 (逆に、ネイティブ ライブラリによって行われたインプロセス環境の変更は、マネージド呼び出し元には表示されません)。

引数が value 空でない場合 (空の値の定義については、このセクションで後述する環境変数の削除に関する説明を参照してください)、 パラメーターによって名前付けされた variable 環境変数が存在しない場合、環境変数が作成され、 の value内容が割り当てられます。 存在する場合は、その値が変更されます。 環境変数は現在のプロセスの環境ブロックでのみ定義されているため、プロセスが終了した後は保持されません。

先頭以外の 16 進ゼロ文字が含まれている場合 variable 、ゼロ文字の前の文字は環境変数名と見なされ、それ以降のすべての文字は無視されます。

先頭以外の 16 進ゼロ文字が含まれている場合 value 、ゼロ文字の前の文字は環境変数に割り当てられ、後続のすべての文字は無視されます。

が空で、 によってvariableという名前の環境変数が存在する場合value、環境変数は削除されます。 が存在しない場合 variable 、操作を実行できない場合でもエラーは発生しません。 value は、次のいずれかの条件で空と見なされます。

  • これは です null
  • これは です String.Empty
  • 値が U+0000 の 1 文字で構成されます。

こちらもご覧ください

適用対象

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

現在のプロセス、または Windows オペレーティング システムのレジストリ キー (現在のユーザー用に予約されているレジストリ キーまたはローカル コンピューター用に予約されているレジストリ キー) に格納される環境変数を作成、変更、または削除します。

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)

パラメーター

variable
String

環境変数の名前。

value
String

variable に割り当てる値。

target
EnvironmentVariableTarget

環境変数の位置を指定する列挙値の 1 つ。

例外

variablenullです。

variable に、長さ 0 の文字列、最初の 16 進数 0 文字 (0x00)、または等号 ("=") が含まれています。

または

variable の長さが 32,767 文字以上です。

または

targetEnvironmentVariableTarget 列挙体のメンバーではありません。

または

targetMachine または Userで、 variable の長さが 255 文字以上です。

または

targetProcess で、 value の長さが 32,767 文字以上です。

または

この操作の実行中にエラーが発生しました。

呼び出し元に、この操作を実行するために必要なアクセス許可がありません。

次の例では、および ターゲットの環境変数をEnvironmentVariableTarget.ProcessEnvironmentVariableTarget.User作成しMachine、オペレーティング システム レジストリにユーザー環境変数とマシン環境変数が含まれているかどうかを確認してから、環境変数を削除します。 Unix に似たシステム上の .NET では、ユーザーごとの環境変数とマシンごとの環境変数はサポートされていないため、 の値EnvironmentVariableTarget.ProcessのみをSetEnvironmentVariable(String, String)SetEnvironmentVariable(String, String, EnvironmentVariableTarget)使用して、環境変数をプロセス環境ブロックに正常に格納します。

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

注釈

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)メソッドを使用すると、現在のプロセスで使用できる環境変数 (値) をProcess定義できます。 現在のプロセス環境ブロックに固有の環境変数は、プロセスが終了するまでのみ保持されます。

さらに、Windows システムでのみ、 メソッドを使用すると、 SetEnvironmentVariable(String, String, EnvironmentVariableTarget) マシン上で実行されるすべてのプロセス (値) と、ユーザーが実行するすべてのプロセス ( EnvironmentVariableTarget.Machine 値) で使用できる環境変数を EnvironmentVariableTarget.User 定義できます。 マシンごとの環境変数とユーザーごとの環境変数は、現在のプロセスの環境ブロックにコピーされます。

Unix に似たシステムでは、 または EnvironmentVariableTarget.User の値EnvironmentVariableTarget.MachineSetEnvironmentVariable(String, String, EnvironmentVariableTarget)持つ メソッドの呼び出しは無視されます。

Unix に似たシステムでは、値 が SetEnvironmentVariable(String, String, EnvironmentVariableTarget)EnvironmentVariableTarget.Process メソッドの呼び出しは、読み込まれるネイティブ ライブラリまたは読み込まれるネイティブ ライブラリには影響しません。 (逆に、ネイティブ ライブラリによって行われたインプロセス環境の変更は、マネージド呼び出し元には表示されません)。

引数が value 空でない場合 (空の値の定義については、このセクションで後述する環境変数の削除に関する説明を参照してください)、 引数によって名前付けされた variable 環境変数が存在しない場合、環境変数が作成され、 の value内容が割り当てられます。 存在する場合は、その値が変更されます。

先頭以外の 16 進ゼロ文字が含まれている場合 variable 、ゼロ文字の前の文字は環境変数名と見なされ、それ以降のすべての文字は無視されます。

先頭以外の 16 進ゼロ文字が含まれている場合 value 、ゼロ文字の前の文字は環境変数に割り当てられ、後続のすべての文字は無視されます。

が空で、 によってvariableという名前の環境変数が存在する場合value、環境変数は削除されます。 value は、次のいずれかの条件で空と見なされます。

  • これは です null
  • これは です String.Empty
  • 値が U+0000 の 1 文字で構成されます。

が存在しない場合 variable 、操作を実行することはできませんが、エラーは発生しません。 が の場合 targetMachine注意してください。これは、現在のプロセスやユーザーだけでなく、ローカル コンピューター全体に影響する環境変数を誤って削除する可能性があるためです。

Windows システムの EnvironmentVariableTarget.Machine と EnvironmentVariableTarget.User

EnvironmentVariableTarget.Userの場合target、環境変数はローカル コンピューターのレジストリの HKEY_CURRENT_USER\Environment キーに格納されます。 また、現在のユーザーとして実行されているエクスプローラーのインスタンスにもコピーされます。 環境変数は、ユーザーがエクスプローラーから起動する新しいプロセスによって継承されます。

同様に、 が EnvironmentVariableTarget.Machineの場合target、環境変数はローカル コンピューターのレジストリの HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment キーに格納されます。 また、エクスプローラーのすべてのインスタンスにもコピーされます。 環境変数は、エクスプローラーから起動された新しいプロセスによって継承されます。

User または Machineの場合target、他のアプリケーションは Windows WM_SETTINGCHANGE メッセージによって設定操作の通知を受け取ります。

EnvironmentVariableTarget.User または EnvironmentVariableTarget.Machineの場合target、 のvalue長さは 2048 文字未満にすることをお勧めします。

こちらもご覧ください

適用対象