Environment.GetEnvironmentVariable Environment.GetEnvironmentVariable Environment.GetEnvironmentVariable Environment.GetEnvironmentVariable Method

Definition

環境変数の値を取得します。 Retrieves the value of an environment variable.

Overloads

GetEnvironmentVariable(String) GetEnvironmentVariable(String) GetEnvironmentVariable(String) GetEnvironmentVariable(String)

現在のプロセスから環境変数の値を取得します。 Retrieves the value of an environment variable from the current process.

GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget)

環境変数の値を取得します。取得する場所として、現在のプロセス、現在のユーザー用に予約されている Windows オペレーティング システムのレジストリ キー、および、ローカル コンピューター用に予約されているレジストリ キーのいずれかを選択できます。 Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.

GetEnvironmentVariable(String) GetEnvironmentVariable(String) GetEnvironmentVariable(String) GetEnvironmentVariable(String)

現在のプロセスから環境変数の値を取得します。 Retrieves the value of an environment variable from the current process.

public:
 static System::String ^ GetEnvironmentVariable(System::String ^ variable);
public static string GetEnvironmentVariable (string variable);
static member GetEnvironmentVariable : string -> string
Public Shared Function GetEnvironmentVariable (variable As String) As String

パラメーター

variable
String String String String

環境変数の名前。 The name of the environment variable.

Returns

variable で指定された環境変数の値。環境変数が見つからない場合は null The value of the environment variable specified by variable, or null if the environment variable is not found.

Exceptions

呼び出し元に、この操作を実行するために必要なアクセス許可がありません。 The caller does not have the required permission to perform this operation.

Examples

次の例では、GetEnvironmentVariableを取得するメソッド、windir環境変数は、Windows ディレクトリのパスが含まれています。The following example uses the GetEnvironmentVariable method to retrieve the windir environment variable, which contains the path of the Windows directory.

using namespace System;
using namespace System::IO;

void main()
{
      // Change the directory to %WINDIR%
      Environment::CurrentDirectory = Environment::GetEnvironmentVariable( "windir" );
      DirectoryInfo^ info = gcnew DirectoryInfo( "." );

      Console::WriteLine("Directory Info:   {0}", info->FullName);
}
// The example displays output like the following:
//        Directory Info:   C:\windows
using System;
using System.IO;

public class Example
{
   public static void Main()
   {
      // Change the directory to %WINDIR%
      Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
      DirectoryInfo info = new DirectoryInfo(".");

      Console.WriteLine("Directory Info:   " + info.FullName);
   }
}
// The example displays output like the following:
//        Directory Info:   C:\windows
Imports System.IO

Module Example
   Public Sub Main()
        ' Change the directory to %WINDIR%
        Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir")
        Dim info As New DirectoryInfo(".")
        Console.WriteLine("Directory Info:   " + info.FullName)
   End Sub
End Module
' The example displays output like the following:
'        Directory Info:   C:\windows

次の例では、という環境変数の値を取得しようとしました。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 its and retrieves its value. この例では、変数の値が表示されます。The example displays the value of the variable. 呼び出す場合は、変数の例では、作成、GetEnvironmentVariables(EnvironmentVariableTarget)メソッドの各メンバーをEnvironmentVariableTarget変数を現在のプロセスの環境ブロックからのみ取得できることを確立するために列挙します。If the example created the variable, it also calls the GetEnvironmentVariables(EnvironmentVariableTarget) method with each member of the EnvironmentVariableTarget enumeration to establish that the variable can be retrieved only from the current process environment block. 最後に、例では、変数を作成、見つかったら削除します。Finally, if the example created the variable, it deletes it.

using System;

public class Example
{
   public static void Main()
   {
      string value;
      bool toDelete = false;
      
      // Check whether the environment variable exists.
      value = Environment.GetEnvironmentVariable("Test1");
      // If necessary, create it.
      if (value == null) {
         Environment.SetEnvironmentVariable("Test1", "Value1");
         toDelete = true;
         
         // Now retrieve it.
         value = Environment.GetEnvironmentVariable("Test1");
      }
      // Display the value.
      Console.WriteLine("Test1: {0}\n", value);
      
      // Confirm that the value can only be retrieved from the process
      // environment block.
      Console.WriteLine("Attempting to retrieve Test1 from:");
      foreach (EnvironmentVariableTarget enumValue in 
                         Enum.GetValues(typeof(EnvironmentVariableTarget))) {
         value = Environment.GetEnvironmentVariable("Test1", enumValue);
         Console.WriteLine("   {0}: {1}", enumValue, 
                           value != null ? value : "not found");
      }
      Console.WriteLine();
      
      // If we've created it, now delete it.
      if (toDelete) { 
         Environment.SetEnvironmentVariable("Test1", null);
         // Confirm the deletion.
         if (Environment.GetEnvironmentVariable("Test1") == null)
            Console.WriteLine("Test1 has been deleted.");
      }         
   }
}
// The example displays the following output:
//       Test1: Value1
//       
//       Attempting to retrieve Test1 from:
//          Process: Value1
//          User: not found
//          Machine: not found
//       
//       Test1 has been deleted.
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: {0}", value)
      Console.WriteLine()
      
      ' Confirm that the value can only be retrieved from the process
      ' environment block.
      Console.WriteLine("Attempting to retrieve Test1 from:")
      For Each enumValue As EnvironmentVariableTarget In 
                         [Enum].GetValues(GetType(EnvironmentVariableTarget))
         value = Environment.GetEnvironmentVariable("Test1", enumValue)
         Console.WriteLine("   {0}: {1}", enumValue, 
                           If(value IsNot Nothing, value, "not found"))
      Next
      Console.WriteLine()
      
      ' 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 output like the following:
'       Test1: Value1
'       
'       Attempting to retrieve Test1 from:
'          Process: Value1
'          User: not found
'          Machine: not found
'       
'       Test1 has been deleted.

Remarks

GetEnvironmentVariable(String)メソッドは、現在のプロセスのみの環境ブロックから環境変数を取得します。The GetEnvironmentVariable(String) method retrieves an environment variable from the environment block of the current process only. 呼び出すことと同じである、GetEnvironmentVariable(String, EnvironmentVariableTarget)メソッドをtarget@propertyEnvironmentVariableTarget.Processします。It is equivalent to calling the GetEnvironmentVariable(String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process.

すべての環境変数と値を取得する、GetEnvironmentVariablesメソッド。To retrieve all environment variables along with their values, call the GetEnvironmentVariables method.

環境変数の名前は、Linux と macOS で大文字小文字が区別されますが、Windows では区別されません。Environment variable names are case-sensitive on Linux and macOS but are not case-sensitive on Windows.

Windows システムでOn Windows systems

Windows システムでは、現在のプロセスの環境ブロックが含まれます。On Windows systems, the environment block of the current process includes:

  • 作成した親プロセスによって用意されたすべての環境変数。All environment variables that are provided to it by the parent process that created it. たとえば、コンソール ウィンドウから起動する、.NET アプリケーションは、コンソール ウィンドウの環境変数のすべてを継承します。For example, a .NET application launched from a console window inherits all of the console window's environment variables.

    親プロセスがない場合は、コンピューターごとおよびユーザーごとの環境変数が代わりに使用されます。If there is no parent process, per-machine and per-user environment variables are used instead. たとえば、新しいコンソール ウィンドウでは、それを起動した時に定義されているすべてのコンピューターごとおよびユーザーごとの環境変数があります。For example, a new console window has all per-machine and per-user environment variables defined at the time it was launched.

  • いずれかを呼び出すことによって、プロセスの実行中には、process ブロックに追加された任意の変数、SetEnvironmentVariable(String, String)メソッドまたはSetEnvironmentVariable(String, String, EnvironmentVariableTarget)メソッドをtargetの値EnvironmentVariableTarget.Processします。Any variables added to the process block while the process is running by calling either the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process. これらの環境変数は、.NET アプリケーションが終了するまで保持されます。These environment variables persist until the .NET application terminates.

呼び出すことによって作成された変数のみを取得するこのメソッドを使用するには、プロセスが開始した後、環境変数が作成する場合、SetEnvironmentVariable(String, String)メソッドまたはSetEnvironmentVariable(String, String, EnvironmentVariableTarget)メソッドをtargetの値。EnvironmentVariableTarget.Processします。If environment variables are created after the process has started, you can use this method to retrieve only those variables that were created by calling the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of .EnvironmentVariableTarget.Process.

MacOS および Linux システムでOn macOS and Linux systems

MacOS および Linux では、現在のプロセスの環境ブロックには、次の環境変数が含まれています。On macOS and Linux, the environment block of the current proccess includes the following environment variables:

.NET core での macOS および Linux コンピューターごとまたはユーザーごとの環境変数をサポートしません。.NET Core on macOS and Linux does not support per-machine or per-user environment variables.

Security

EnvironmentPermission
値を読み取る機能のvariableします。 for the ability to read the value of variable. 関連付けられた列挙体。 Read Associated enumeration: Read

See Also

GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget) GetEnvironmentVariable(String, EnvironmentVariableTarget)

環境変数の値を取得します。取得する場所として、現在のプロセス、現在のユーザー用に予約されている Windows オペレーティング システムのレジストリ キー、および、ローカル コンピューター用に予約されているレジストリ キーのいずれかを選択できます。 Retrieves the value of an environment variable from the current process or from the Windows operating system registry key for the current user or local machine.

public:
 static System::String ^ GetEnvironmentVariable(System::String ^ variable, EnvironmentVariableTarget target);
public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target);
static member GetEnvironmentVariable : string * EnvironmentVariableTarget -> string
Public Shared Function GetEnvironmentVariable (variable As String, target As EnvironmentVariableTarget) As String

パラメーター

variable
String String String String

環境変数の名前。 The name of an environment variable.

Returns

variable パラメーターと target パラメーターで指定された環境変数の値。環境変数が見つからない場合は null The value of the environment variable specified by the variable and target parameters, or null if the environment variable is not found.

Exceptions

target は有効な EnvironmentVariableTarget 値ではありません。 target is not a valid EnvironmentVariableTarget value.

呼び出し元に、この操作を実行するために必要なアクセス許可がありません。 The caller does not have the required permission to perform this operation.

Examples

次の例では、プロセス、ユーザー、およびマシンのターゲット用の環境変数を作成します。、オペレーティング システムのレジストリがユーザーとコンピューターの環境変数が含まれていますし、環境変数を削除するかどうかを確認します。The following example creates environment variables for the Process, User, and Machine targets, checks whether the operating system registry contains the User and Machine environment variables, then deletes the environment variables.

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

using namespace System;
using namespace System::Collections;
using namespace Microsoft::Win32;

namespace EnvironmentVariablesSample
{
    public ref class TestEnvironmentVariables sealed
    {
    public:
        // DoTest: Test get/set environment variables
        static void DoTest()
        {     
            // 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^ messageStep1 = "Step 1:\n"
                "  Check whether the environment variables already"
                " exist in \n"
                "  the various targets...\n";
            String^ messageStep2 = "Step 2:\n"
                "  Set the environment variable for each"
                " target...\n";
            String^ messageStep3Part1 = "Step 3, part 1:\n"
                "  Display the environment variables in each"
                " target...\n";
            String^ messageStep3Part2 = "Step 3, part 2:\n"
                "  Check whether the User and Machine "
                " environment variables \n"
                "  were created in the Windows operating"
                " system registry...\n";
            String^ messageStep4Part1 = "Step 4, part 1:\n"
                "  Delete the environment variables created "
                "for this sample...\n";
            String^ messageStep4Part2 = "Step 4, part 2:\n"
                "  Check whether the environment variables were "
                "deleted \n"
                "  in each target...\n";
            String^ messageStep4Part3 = "Step 4, part 3:\n"
                "  Check whether the User and Machine environment "
                "variables \n"
                "  were deleted from the Windows operating system "
                "registry...\n";
            String^ step2Format = "  {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(messageStep1);
            CheckVariables();
            Console::WriteLine();   

            // Step 2:
            // Set the environment variable for each target.
            // This section demonstrates
            // Environment.SetEnvironmentVariable.
            Console::WriteLine(messageStep2);     

            // Set the environment variable for the default target
            // (the current process).
            Console::WriteLine(step2Format, "(default)", VariableA,
                existsA);
            Environment::SetEnvironmentVariable(VariableA, existsA);  

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

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

            // Set the environment variable for the local machine.
            Console::WriteLine(step2Format, "Machine", VariableD,
                existsD);
            Environment::SetEnvironmentVariable(VariableD, existsD,
                EnvironmentVariableTarget::Machine);
            Console::WriteLine();      

            // Step 3, part 1:
            // Display the environment variables in each target.
            Console::WriteLine(messageStep3Part1);
            PrintVariables();
            Console::WriteLine();     

            // Step 3, part 2:
            // Check whether the User and Machine environment
            // variables were created in the Windows operating system
            // registry.
            Console::WriteLine(messageStep3Part2);
            CheckRegistryVariables();
            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(messageStep4Part1);
            Environment::SetEnvironmentVariable(VariableA, nullptr);
            Environment::SetEnvironmentVariable(VariableB, nullptr,
                EnvironmentVariableTarget::Process);
            Environment::SetEnvironmentVariable(VariableC, nullptr,
                EnvironmentVariableTarget::User);
            Environment::SetEnvironmentVariable(VariableD, nullptr,
                EnvironmentVariableTarget::Machine);     

            // Step 4, part 2:
            // Check whether the environment variables were deleted 
            // in each target.
            Console::WriteLine(messageStep4Part2);
            CheckVariables();

            // Step 4, part 3:
            // Check whether the User and Machine environment
            // variables were deleted from the Windows operating
            // system registry.
            Console::WriteLine(messageStep4Part3);
            CheckRegistryVariables();
        }

    protected:
        // Globals:
        literal String^ NameValueFormat = "  {0} {1}.";
        literal String^ VariableSuffix = "_GETSET_ENVAR_SAMPLE";

        // Four relatively unique environment variable names.
        // default process

        literal String^ VariableA = "A_GETSET_ENVAR_SAMPLE";

        // Current Process
        literal String^ VariableB = "B_GETSET_ENVAR_SAMPLE";

        // Current User
        literal String^ VariableC = "C_GETSET_ENVAR_SAMPLE";

        // Local Machine
        literal String^ VariableD = "D_GETSET_ENVAR_SAMPLE";

    private:
        // CheckVariablesInTarget:
        // Test whether a specific environment variable exists
        // in a target. This section demonstrates
        // Environment.GetEnvironmentVariable.
        static void CheckVariablesInTarget(String^ variable,
            EnvironmentVariableTarget target)
        {
            String^ variableName;

            // Zero means use the default target.
            if (target == (EnvironmentVariableTarget) 0)
            {
                variableName =
                    Environment::GetEnvironmentVariable(variable);
            }
            else
            {
                variableName = Environment::GetEnvironmentVariable(
                    variable, target);
            }
            Console::WriteLine(NameValueFormat, variable,
                (String::IsNullOrEmpty(variableName) ?
                "doesn't exist" : variableName));
        }

        // CheckVariable:
        // Uses CheckVariablesInTarget to test whether each
        // environment variable exists in a target.
        static void CheckVariables()
        {
            Console::WriteLine("Process:");

            // Check the default target(current process)
            CheckVariablesInTarget(VariableA,
                (EnvironmentVariableTarget) 0);
            CheckVariablesInTarget(VariableB,
                EnvironmentVariableTarget::Process);
            CheckVariablesInTarget(VariableC,
                EnvironmentVariableTarget::Process);
            CheckVariablesInTarget(VariableD,
                EnvironmentVariableTarget::Process);
            Console::WriteLine();

            Console::WriteLine("User:");
            CheckVariablesInTarget(VariableA,
                EnvironmentVariableTarget::User);
            CheckVariablesInTarget(VariableB,
                EnvironmentVariableTarget::User);
            CheckVariablesInTarget(VariableC,
                EnvironmentVariableTarget::User);
            CheckVariablesInTarget(VariableD,
                EnvironmentVariableTarget::User);
            Console::WriteLine();

            Console::WriteLine("Machine:");
            CheckVariablesInTarget(VariableA,
                EnvironmentVariableTarget::Machine);
            CheckVariablesInTarget(VariableB,
                EnvironmentVariableTarget::Machine);
            CheckVariablesInTarget(VariableC,
                EnvironmentVariableTarget::Machine);
            CheckVariablesInTarget(VariableD,
                EnvironmentVariableTarget::Machine);
            Console::WriteLine();
        }

        // PrintVariablesFromTarget: PrintVariables helper function.
        // This section demonstrates
        // Environment.GetEnvironmentVariables.
        static void PrintVariablesFromTarget(
            EnvironmentVariableTarget target)
        {
            String^ valueString;
            String^ keyString;

            for each (DictionaryEntry^ dictionary in
                Environment::GetEnvironmentVariables(target))
            {
                keyString = safe_cast<String^> (dictionary->Key);
                valueString = safe_cast<String^> (dictionary->Value);
                if (keyString->Contains(VariableSuffix))
                    Console::WriteLine(NameValueFormat, keyString,
                    valueString);
            }
            Console::WriteLine();
        }

        // PrintVariables:
        // Uses PrintVariablesFromTarget to test whether
        // each environment variable exists in a target.
        static void PrintVariables()
        {
            Console::WriteLine("Process:");
            PrintVariablesFromTarget(EnvironmentVariableTarget::Process);

            Console::WriteLine("User:");
            PrintVariablesFromTarget(EnvironmentVariableTarget::User);

            Console::WriteLine("Machine:");
            PrintVariablesFromTarget(EnvironmentVariableTarget::Machine);
        }

        // CheckRegistryVariablesForKey: CheckRegistryVariables
        // helper function. This function filters out irrelevant
        // environment variables.
        static void CheckRegistryVariablesForKey(RegistryKey^ targetKey)
        {
            bool exists = false;            

            for each (
                String^ variableName in targetKey->GetValueNames())
            {
                if (variableName->Contains(VariableSuffix))
                {
                    String^ variableValue =
                        safe_cast<String^>
                        (targetKey->GetValue(variableName));
                    Console::WriteLine(NameValueFormat, variableName,
                        variableValue);
                    exists = true;
                }
            }
            if (!exists)
            {
                Console::WriteLine(
                    "  Environment variable doesn't exist.");
            }
            Console::WriteLine();
        }

        // CheckRegistryVariables:
        // Uses CheckRegistryVariables to display the User and
        // Machine environment variables in the registry.
        static void CheckRegistryVariables()
        {
            String^ subkeyUser = "Environment";
            String^ subkeyMachine = "System\\CurrentControlSet\\"
                "Control\\Session Manager\\Environment";
            String^ subkeyFormat = "\"{0}\" key:";

            Console::WriteLine(subkeyFormat, subkeyUser);
            CheckRegistryVariablesForKey(
                Registry::CurrentUser->OpenSubKey(subkeyUser));

            Console::WriteLine(subkeyFormat, subkeyMachine);
            CheckRegistryVariablesForKey(
                Registry::LocalMachine->OpenSubKey(subkeyMachine));
        }
    };
};

using namespace EnvironmentVariablesSample;

int main()
{
    TestEnvironmentVariables::DoTest();
}

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


// 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 current process.
    Console.WriteLine(fmt2x, "Process", myVarB, existsB);
    Environment.SetEnvironmentVariable(myVarB, existsB, 
        EnvironmentVariableTarget.Process);

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

// Set the environment variable for 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.
*/
' This example demonstrates the 
'     Environment.GetEnvironmentVariable,
'     Environment.SetEnvironmentVariable, and 
'     Environment.GetEnvironmentVariables overloaded methods.
Imports System
Imports System.Collections
Imports Microsoft.Win32
Imports Microsoft.VisualBasic

Class Sample
   '-------------------------------------------------------------------------------------
   ' Globals: 
   '-------------------------------------------------------------------------------------
   Protected Shared fmtNameValue As String = "  {0} {1}."
   Protected Shared myVarSuffix As String = "_GETSET_ENVAR_SAMPLE"
   
   ' Four relatively unique environment variable names.
   Protected Shared myVarA As String = "A" & myVarSuffix ' default process
   Protected Shared myVarB As String = "B" & myVarSuffix ' Current Process
   Protected Shared myVarC As String = "C" & myVarSuffix ' Current User
   Protected Shared myVarD As String = "D" & myVarSuffix ' Local Machine
   '=====================================================================================
   ' EachVariable: 
   ' Test whether a specific environment variable exists in a target.
   ' This section demonstrates Environment.GetEnvironmentVariable.
   '-------------------------------------------------------------------------------------
   Protected Shared Sub EachVariable(var As String, tgt As EnvironmentVariableTarget)
      Dim str As String
      '
      If 0 = tgt Then ' Zero means use the default target.
         str = Environment.GetEnvironmentVariable(var)
      Else
         str = Environment.GetEnvironmentVariable(var, tgt)
      End If
      Console.WriteLine(fmtNameValue, var, IIf(String.IsNullOrEmpty(str), _
                                              "doesn't exist", str))
   End Sub 'EachVariable
   
   '-------------------------------------------------------------------------------------
   ' CheckEachVariable: 
   ' Uses EachVariable to test whether each environment variable exists in a target.
   '-------------------------------------------------------------------------------------
   Protected Shared Sub 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()
   End Sub 'CheckEachVariable
   
   '=====================================================================================
   ' AllVariables: CheckAllVariables helper function.
   ' This section demonstrates Environment.GetEnvironmentVariables.
   '-------------------------------------------------------------------------------------
   Private Shared Sub AllVariables(tgt As EnvironmentVariableTarget)
      Dim value As String
      Dim key As String
      
      Dim de As DictionaryEntry
      For Each de In Environment.GetEnvironmentVariables(tgt)
         key = CStr(de.Key)
         value = CStr(de.Value)
         If key.Contains(myVarSuffix) Then
            Console.WriteLine(fmtNameValue, key, value)
         End If
      Next de
      Console.WriteLine()
   End Sub 'AllVariables
   
   '=====================================================================================
   ' CheckAllVariables: 
   ' Uses AllVariables to test whether each environment variable exists in a target.
   '-------------------------------------------------------------------------------------
   Protected Shared Sub CheckAllVariables()
      Console.WriteLine("Process:")
      AllVariables(EnvironmentVariableTarget.Process)
      
      Console.WriteLine("User:")
      AllVariables(EnvironmentVariableTarget.User)
      
      Console.WriteLine("Machine:")
      AllVariables(EnvironmentVariableTarget.Machine)
   End Sub 'CheckAllVariables
   
   '=====================================================================================
   ' ChkReg: CheckRegistry helper function.
   ' This function filters out irrelevant environment variables. 
   '-------------------------------------------------------------------------------------
   Private Shared Sub ChkReg(rk As RegistryKey)
      Dim exists As Boolean = False
      Dim registryNone As String = "  Environment variable doesn't exist."
      
      Dim s As String
      For Each s In rk.GetValueNames()
         If s.Contains(myVarSuffix) Then
            Console.WriteLine(fmtNameValue, s, CStr(rk.GetValue(s)))
            exists = True
         End If
      Next s
      If exists = False Then
         Console.WriteLine(registryNone)
      End If
      Console.WriteLine()
   End Sub 'ChkReg
   
   '-------------------------------------------------------------------------------------
   ' CheckRegistry: 
   ' Uses ChkReg to display the User and Machine environment variables in the registry.
   '-------------------------------------------------------------------------------------
   Protected Shared Sub CheckRegistry()
      Dim subkeyU As String = "Environment"
      Dim subkeyM As String = "System\CurrentControlSet\Control\Session Manager\Environment"
      Dim fmtSubkey As String = """{0}"" key:"
      
      Console.WriteLine(fmtSubkey, subkeyU)
      ChkReg(Registry.CurrentUser.OpenSubKey(subkeyU))
      
      Console.WriteLine(fmtSubkey, subkeyM)
      ChkReg(Registry.LocalMachine.OpenSubKey(subkeyM))
   End Sub 'CheckRegistry
   
   '=====================================================================================
   ' Main:
   '-------------------------------------------------------------------------------------
   Public Shared Sub Main()
      '-------------------------------------------------------------------------------------
      ' Environment variable values
      '-------------------------------------------------------------------------------------
      Dim existsA As String = "exists in the default target (Process)"
      Dim existsB As String = "exists in Process"
      Dim existsC As String = "exists in User"
      Dim existsD As String = "exists in Machine"
      '-------------------------------------------------------------------------------------
      ' Messages:
      '-------------------------------------------------------------------------------------
      Dim msg1  As String = "Step 1:" & vbCrLf & _
                            "  Check whether the environment variables already exist in " _
                 & vbCrLf & "  the various targets..." & vbCrLf
      Dim msg2  As String = "Step 2:" & vbCrLf & _
                            "  Set the environment variable for each target..." & vbCrLf
      Dim msg31 As String = "Step 3, part 1:" & vbCrLf & _
                            "  Display the environment variables in each target..." & vbCrLf
      Dim msg32 As String = "Step 3, part 2:" & vbCrLf & _
                            "  Check whether the User and Machine environment variables " _
                 & vbCrLf & "  were created in the Windows operating system registry..." _
                 & vbCrLf
      Dim msg41 As String = "Step 4, part 1:" & vbCrLf & _
                            "  Delete the environment variables created for this sample..." _
                 & vbCrLf
      Dim msg42 As String = "Step 4, part 2:" & vbCrLf & _
                            "  Check whether the environment variables were deleted " _
                 & vbCrLf & "  in each target..." & vbCrLf
      Dim msg43 As String = "Step 4, part 3:" & vbCrLf & _
                            "  Check whether the User and Machine environment variables " _
                 & vbCrLf & "  were deleted from the Windows operating system registry..." _
                 & vbCrLf
      Dim fmt2x As String = "  {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 current process.
      Console.WriteLine(fmt2x, "Process", myVarB, existsB)
      Environment.SetEnvironmentVariable(myVarB, existsB, EnvironmentVariableTarget.Process)
      
      ' Set the environment variable for the current user.
      Console.WriteLine(fmt2x, "User", myVarC, existsC)
      Environment.SetEnvironmentVariable(myVarC, existsC, EnvironmentVariableTarget.User)
      
      ' Set the environment variable for 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, Nothing)
      Environment.SetEnvironmentVariable(myVarB, Nothing, EnvironmentVariableTarget.Process)
      Environment.SetEnvironmentVariable(myVarC, Nothing, EnvironmentVariableTarget.User)
      Environment.SetEnvironmentVariable(myVarD, Nothing, 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()
   End Sub 'Main
End Class 'Sample
'
'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.
'

Remarks

すべての環境変数と値を取得する、GetEnvironmentVariablesメソッド。To retrieve all environment variables along with their values, call the GetEnvironmentVariables method.

環境変数の名前は、Linux と macOS で大文字小文字が区別されますが、Windows では区別されません。Environment variable names are case-sensitive on Linux and macOS but are not case-sensitive on Windows.

Windows システムでOn Windows systems

Windows では、上、targetパラメーターは、現在のプロセスまたは現在のユーザーまたはローカル コンピューターの Windows オペレーティング システムのレジストリ キーから、環境変数が取得されるかどうかを指定します。On Windows, the target parameter specifies whether the environment variable is retrieved from the current process or from the Windows operating system registry key for the current user or local machine. ユーザーごとおよびコンピューターごとのすべての環境変数は、.NET プロセスを作成した親プロセスに使用できるその他の環境変数が、現在のプロセスの環境ブロックに自動的にコピーします。All per-user and per-machine environment variables are automatically copied into the environment block of the current process, as are any other environment variables that are available to the parent process that created the .NET process. いずれかを呼び出して環境変数を現在のプロセスの環境ブロックにのみ追加ただし、SetEnvironmentVariable(String, String)メソッドまたはSetEnvironmentVariable(String, String, EnvironmentVariableTarget)メソッドをtargetの値EnvironmentVariableTarget.Processプロセスの間だけ持続します。However, environment variables added only to the environment block of the current process by calling either the SetEnvironmentVariable(String, String) method or the SetEnvironmentVariable(String, String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.Process persist only for the duration of the process.

MacOS および Linux システムでOn macOS and Linux systems

MacOS および Linux 上のGetEnvironmentVariable(String, EnvironmentVariableTarget)メソッドのサポート、targetの値Processのみ。On macOS and Linux, the GetEnvironmentVariable(String, EnvironmentVariableTarget) method supports a target value of Process only. 呼び出し、targetの値MachineまたはUserはサポートされていませんし、返すnullします。Calls with a target value of Machine or User are not supported and return null.

プロセスごとの環境変数は次のとおりです。Per-process environment variables are:

Security

EnvironmentPermission
値を読み取る機能のvariable場合targetProcess(列挙型に関連付けられている: Read)、 for the ability to read the value of variable if target is Process (Associated enumeration: Read), または or 環境変数へのフル アクセスの場合はtargetUserまたはMachine(列挙型に関連付けられている: Unrestricted)。 for full access to environment variables if target is User or Machine (Associated enumeration: Unrestricted).

See Also

Applies to