Compartir a través de


Environment.GetEnvironmentVariables Método

Definición

Recupera todos los nombres de las variables de entorno y sus valores.

Sobrecargas

GetEnvironmentVariables()

Recupera todos los nombres de las variables de entorno y sus valores del proceso actual.

GetEnvironmentVariables(EnvironmentVariableTarget)

Recupera todos los nombres de las variables de entorno y sus valores del proceso actual o de la clave del Registro del sistema operativo Windows para la máquina local o el usuario actual.

GetEnvironmentVariables()

Source:
Environment.Variables.Windows.cs
Source:
Environment.Variables.Windows.cs
Source:
Environment.Variables.Windows.cs

Recupera todos los nombres de las variables de entorno y sus valores del proceso actual.

public:
 static System::Collections::IDictionary ^ GetEnvironmentVariables();
public static System.Collections.IDictionary GetEnvironmentVariables ();
static member GetEnvironmentVariables : unit -> System.Collections.IDictionary
Public Shared Function GetEnvironmentVariables () As IDictionary

Devoluciones

Un diccionario que contiene todos los nombres de las variables de entorno y sus valores; de lo contrario, un diccionario vacío si no se encuentra ninguna variable de entorno.

Excepciones

El autor de la llamada no tiene el permiso requerido para llevar a cabo esta operación.

El búfer no tiene memoria.

Ejemplos

En el siguiente ejemplo se muestra el GetEnvironmentVariables método.

using namespace System;
using namespace System::Collections;

int main()
{
   Console::WriteLine( "GetEnvironmentVariables: " );
   for each (DictionaryEntry^ de in Environment::GetEnvironmentVariables())
      Console::WriteLine( " {0} = {1}", de->Key, de->Value );
}
// Output from the example is not shown, since it is:
//    Lengthy.
//    Specific to the machine on which the example is run.
//    May reveal information that should remain secure.
// Sample for the Environment.GetEnvironmentVariables method
using System;
using System.Collections;

class Sample
{
    public static void Main()
    {
       Console.WriteLine();
       Console.WriteLine("GetEnvironmentVariables: ");
       foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
           Console.WriteLine("  {0} = {1}", de.Key, de.Value);
    }
}
// Output from the example is not shown, since it is:
//    Lengthy.
//    Specific to the machine on which the example is run.
//    May reveal information that should remain secure.
// Sample for the Environment.GetEnvironmentVariables method
open System
open System.Collections

printfn "\nGetEnvironmentVariables: "
for de in Environment.GetEnvironmentVariables() do
    let de = de :?> DictionaryEntry
    printfn $"  {de.Key} = {de.Value}"
// Output from the example is not shown, since it is:
//    Lengthy.
//    Specific to the machine on which the example is run.
//    May reveal information that should remain secure.
' Sample for the Environment.GetEnvironmentVariables method
Imports System.Collections

Class Sample
   Public Shared Sub Main()
      Console.WriteLine("GetEnvironmentVariables: ")
      For Each de As DictionaryEntry In Environment.GetEnvironmentVariables()
         Console.WriteLine("  {0} = {1}", de.Key, de.Value)
      Next 
   End Sub 
End Class 
' Output from the example is not shown, since it is:
'    Lengthy.
'    Specific to the machine on which the example is run.
'    May reveal information that should remain secure.

Comentarios

Los nombres y valores de las variables de entorno se almacenan como pares clave-valor en el devuelto IDictionary.

En sistemas Windows

En los sistemas Windows, el GetEnvironmentVariables método devuelve las siguientes variables de entorno:

En sistemas similares a Unix

En sistemas similares a Unix, el GetEnvironmentVariables método recupera el nombre y el valor de todas las variables de entorno que se heredan del proceso primario que inició el dotnet proceso o que se definen dentro del ámbito del dotnet propio proceso. Una vez finalizado el dotnet proceso, estas últimas variables de entorno dejan de existir.

.NET que se ejecuta en sistemas similares a Unix no admite variables de entorno por máquina o por usuario.

Nota

En sistemas similares a Unix, los autores de llamadas administrados no ven las modificaciones del entorno en proceso realizadas por bibliotecas nativas.

Consulte también

Se aplica a

GetEnvironmentVariables(EnvironmentVariableTarget)

Source:
Environment.cs
Source:
Environment.cs
Source:
Environment.cs

Recupera todos los nombres de las variables de entorno y sus valores del proceso actual o de la clave del Registro del sistema operativo Windows para la máquina local o el usuario actual.

public:
 static System::Collections::IDictionary ^ GetEnvironmentVariables(EnvironmentVariableTarget target);
public static System.Collections.IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target);
static member GetEnvironmentVariables : EnvironmentVariableTarget -> System.Collections.IDictionary
Public Shared Function GetEnvironmentVariables (target As EnvironmentVariableTarget) As IDictionary

Parámetros

target
EnvironmentVariableTarget

Uno de los valores de EnvironmentVariableTarget. Solo Process se admite en .NET que se ejecuta en sistemas similares a Unix.

Devoluciones

Un diccionario que contiene todos los nombres de las variables de entorno y sus valores del origen especificado por el parámetro target; de lo contrario, un diccionario vacío si no se encuentra ninguna variable de entorno.

Excepciones

El llamador no dispone del permiso requerido para llevar a cabo esta operación para el valor especificado de target.

target contiene un valor no válido.

Ejemplos

En el ejemplo siguiente se crean variables de entorno para los EnvironmentVariableTarget.Processdestinos , EnvironmentVariableTarget.Usery Machine , se comprueba si el registro del sistema operativo contiene las variables de entorno de usuario y máquina y, a continuación, elimina las variables de entorno. Dado que .NET en sistemas similares a Unix no admite variables de entorno por usuario y por equipo, solo SetEnvironmentVariable(String, String) y SetEnvironmentVariable(String, String, EnvironmentVariableTarget) con un valor de almacenar correctamente una variable de EnvironmentVariableTarget.Process entorno en el bloque de entorno de proceso.

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

Comentarios

Los nombres y valores de las variables de entorno se almacenan como pares clave-valor en el objeto devuelto IDictionary .

En sistemas Windows

En los sistemas Windows, el target parámetro especifica si el origen es el proceso actual, la clave del Registro para el usuario actual o la clave del Registro para el equipo local.

En sistemas similares a Unix

En sistemas similares a Unix, solo se admite un target valor de EnvironmentVariableTarget.Process . Las variables de entorno por proceso se heredan del proceso primario (normalmente el shell) que se usa para iniciar el dotnet proceso o se definen dentro del ámbito del dotnet propio proceso. Una vez finalizado el proceso de dotnet, estas últimas variables de entorno dejan de existir.

No se admiten variables de entorno por máquina y por usuario. Valor target de EnvironmentVariableTarget.Machine o EnvironmentVariableTarget.User devuelve una matriz vacía.

Nota

En sistemas similares a Unix, los autores de llamadas administrados no ven las modificaciones del entorno en proceso realizadas por bibliotecas nativas.

Consulte también

Se aplica a