Environment Environment Environment Environment Class

Definición

Proporciona información acerca del entorno y la plataforma actuales, y la forma de manipularlos.Provides information about, and means to manipulate, the current environment and platform. Esta clase no puede heredarse.This class cannot be inherited.

public ref class Environment abstract sealed
[System.Runtime.InteropServices.ComVisible(true)]
public static class Environment
type Environment = class
Public Class Environment
Herencia
EnvironmentEnvironmentEnvironmentEnvironment
Atributos

Ejemplos

En el ejemplo siguiente se muestra una lista de información sobre el entorno actual.The following example demonstrates displays a list of information about the current environment.

// Sample for Environment class summary
using namespace System;
using namespace System::Collections;
int main()
{
   String^ str;
   String^ nl = Environment::NewLine;
   
   //
   Console::WriteLine();
   Console::WriteLine( "-- Environment members --" );
   
   //  Invoke this sample with an arbitrary set of command line arguments.
   Console::WriteLine( "CommandLine: {0}", Environment::CommandLine );
   array<String^>^arguments = Environment::GetCommandLineArgs();
   Console::WriteLine( "GetCommandLineArgs: {0}", String::Join( ", ", arguments ) );
   
   //  <-- Keep this information secure! -->
   Console::WriteLine( "CurrentDirectory: {0}", Environment::CurrentDirectory );
   Console::WriteLine( "ExitCode: {0}", Environment::ExitCode );
   Console::WriteLine( "HasShutdownStarted: {0}", Environment::HasShutdownStarted );
   
   //  <-- Keep this information secure! -->
   Console::WriteLine( "MachineName: {0}", Environment::MachineName );
   Console::WriteLine( "NewLine: {0}  first line {0}  second line {0}  third line", Environment::NewLine );
   Console::WriteLine( "OSVersion: {0}", Environment::OSVersion );
   Console::WriteLine( "StackTrace: ' {0}'", Environment::StackTrace );
   
   //  <-- Keep this information secure! -->
   Console::WriteLine( "SystemDirectory: {0}", Environment::SystemDirectory );
   Console::WriteLine( "TickCount: {0}", Environment::TickCount );
   
   //  <-- Keep this information secure! -->
   Console::WriteLine( "UserDomainName: {0}", Environment::UserDomainName );
   Console::WriteLine( "UserInteractive: {0}", Environment::UserInteractive );
   
   //  <-- Keep this information secure! -->
   Console::WriteLine( "UserName: {0}", Environment::UserName );
   Console::WriteLine( "Version: {0}", Environment::Version );
   Console::WriteLine( "WorkingSet: {0}", Environment::WorkingSet );
   
   //  No example for Exit(exitCode) because doing so would terminate this example.
   //  <-- Keep this information secure! -->
   String^ query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
   str = Environment::ExpandEnvironmentVariables( query );
   Console::WriteLine( "ExpandEnvironmentVariables: {0} {1}", nl, str );
   Console::WriteLine( "GetEnvironmentVariable: {0}  My temporary directory is {1}.", nl, Environment::GetEnvironmentVariable( "TEMP" ) );
   Console::WriteLine( "GetEnvironmentVariables: " );
   IDictionary^ environmentVariables = Environment::GetEnvironmentVariables();
   IEnumerator^ myEnum = environmentVariables->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DictionaryEntry^ de = safe_cast<DictionaryEntry^>(myEnum->Current);
      Console::WriteLine( " {0} = {1}", de->Key, de->Value );
   }

   Console::WriteLine( "GetFolderPath: {0}", Environment::GetFolderPath( Environment::SpecialFolder::System ) );
   array<String^>^drives = Environment::GetLogicalDrives();
   Console::WriteLine( "GetLogicalDrives: {0}", String::Join( ", ", drives ) );
}

/*
This example produces results similar to the following:
(Any result that is lengthy or reveals information that should remain 
secure has been omitted and marked S"!---OMITTED---!".)

C:\>env0 ARBITRARY TEXT

-- Environment members --
CommandLine: env0 ARBITRARY TEXT
GetCommandLineArgs: env0, ARBITRARY, TEXT
CurrentDirectory: C:\Documents and Settings\!---OMITTED---!
ExitCode: 0
HasShutdownStarted: False
MachineName: !---OMITTED---!
NewLine:
  first line
  second line
  third line
OSVersion: Microsoft Windows NT 5.1.2600.0
StackTrace: '   at System::Environment::GetStackTrace(Exception e)
   at System::Environment::GetStackTrace(Exception e)
   at System::Environment::get_StackTrace()
   at Sample::Main()'
SystemDirectory: C:\WINNT\System32
TickCount: 17995355
UserDomainName: !---OMITTED---!
UserInteractive: True
UserName: !---OMITTED---!
Version: !---OMITTED---!
WorkingSet: 5038080
ExpandEnvironmentVariables:
  My system drive is C: and my system root is C:\WINNT
GetEnvironmentVariable:
  My temporary directory is C:\DOCUME~1\!---OMITTED---!\LOCALS~1\Temp.
GetEnvironmentVariables:
  !---OMITTED---!
GetFolderPath: C:\WINNT\System32
GetLogicalDrives: A:\, C:\, D:\

*/
// Sample for Environment class summary
using System;
using System.Collections;

class Sample
{
    public static void Main()
    {
        string str;
        string nl = Environment.NewLine;
        //
        Console.WriteLine();
        Console.WriteLine("-- Environment members --");

        //  Invoke this sample with an arbitrary set of command line arguments.
        Console.WriteLine("CommandLine: {0}", Environment.CommandLine);

        string[] arguments = Environment.GetCommandLineArgs();
        Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));

        //  <-- Keep this information secure! -->
        Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);

        Console.WriteLine("ExitCode: {0}", Environment.ExitCode);

        Console.WriteLine("HasShutdownStarted: {0}", Environment.HasShutdownStarted);

        //  <-- Keep this information secure! -->
        Console.WriteLine("MachineName: {0}", Environment.MachineName);

        Console.WriteLine("NewLine: {0}  first line{0}  second line{0}  third line",
                              Environment.NewLine);

        Console.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString());

        Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);

        //  <-- Keep this information secure! -->
        Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);

        Console.WriteLine("TickCount: {0}", Environment.TickCount);

        //  <-- Keep this information secure! -->
        Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);

        Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);

        //  <-- Keep this information secure! -->
        Console.WriteLine("UserName: {0}", Environment.UserName);

        Console.WriteLine("Version: {0}", Environment.Version.ToString());

        Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet);

        //  No example for Exit(exitCode) because doing so would terminate this example.

        //  <-- Keep this information secure! -->
        string query = "My system drive is %SystemDrive% and my system root is %SystemRoot%";
        str = Environment.ExpandEnvironmentVariables(query);
        Console.WriteLine("ExpandEnvironmentVariables: {0}  {1}", nl, str);

        Console.WriteLine("GetEnvironmentVariable: {0}  My temporary directory is {1}.", nl,
                               Environment.GetEnvironmentVariable("TEMP"));

        Console.WriteLine("GetEnvironmentVariables: ");
        IDictionary environmentVariables = Environment.GetEnvironmentVariables();
        foreach (DictionaryEntry de in environmentVariables)
        {
            Console.WriteLine("  {0} = {1}", de.Key, de.Value);
        }

        Console.WriteLine("GetFolderPath: {0}",
                     Environment.GetFolderPath(Environment.SpecialFolder.System));

        string[] drives = Environment.GetLogicalDrives();
        Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
    }
}
/*
This example produces results similar to the following:
(Any result that is lengthy or reveals information that should remain 
secure has been omitted and marked "!---OMITTED---!".)

C:\>env0 ARBITRARY TEXT

-- Environment members --
CommandLine: env0 ARBITRARY TEXT
GetCommandLineArgs: env0, ARBITRARY, TEXT
CurrentDirectory: C:\Documents and Settings\!---OMITTED---!
ExitCode: 0
HasShutdownStarted: False
MachineName: !---OMITTED---!
NewLine:
  first line
  second line
  third line
OSVersion: Microsoft Windows NT 5.1.2600.0
StackTrace: '   at System.Environment.GetStackTrace(Exception e)
   at System.Environment.GetStackTrace(Exception e)
   at System.Environment.get_StackTrace()
   at Sample.Main()'
SystemDirectory: C:\WINNT\System32
TickCount: 17995355
UserDomainName: !---OMITTED---!
UserInteractive: True
UserName: !---OMITTED---!
Version: !---OMITTED---!
WorkingSet: 5038080
ExpandEnvironmentVariables:
  My system drive is C: and my system root is C:\WINNT
GetEnvironmentVariable:
  My temporary directory is C:\DOCUME~1\!---OMITTED---!\LOCALS~1\Temp.
GetEnvironmentVariables: 
  !---OMITTED---!
GetFolderPath: C:\WINNT\System32
GetLogicalDrives: A:\, C:\, D:\

*/
' Sample for Environment class summary
Imports System.Collections

Class Sample
   Public Shared Sub Main()
      Dim str As [String]
      Dim nl As [String] = Environment.NewLine
      '
      Console.WriteLine()
      Console.WriteLine("-- Environment members --")
      
      '  Invoke this sample with an arbitrary set of command line arguments.
      Console.WriteLine("CommandLine: {0}", Environment.CommandLine)
      
      Dim arguments As [String]() = Environment.GetCommandLineArgs()
      Console.WriteLine("GetCommandLineArgs: {0}", [String].Join(", ", arguments))
      
      '  <-- Keep this information secure! -->
      Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory)
      
      Console.WriteLine("ExitCode: {0}", Environment.ExitCode)
      
      Console.WriteLine("HasShutdownStarted: {0}", Environment.HasShutdownStarted)
      
      '  <-- Keep this information secure! -->
      Console.WriteLine("MachineName: {0}", Environment.MachineName)
      
      Console.WriteLine("NewLine: {0}  first line{0}  second line{0}" & _
                        "  third line", Environment.NewLine)
      
      Console.WriteLine("OSVersion: {0}", Environment.OSVersion.ToString())
      
      Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace)
      
      '  <-- Keep this information secure! -->
      Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory)
      
      Console.WriteLine("TickCount: {0}", Environment.TickCount)
      
      '  <-- Keep this information secure! -->
      Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName)
      
      Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive)
      
      '  <-- Keep this information secure! -->
      Console.WriteLine("UserName: {0}", Environment.UserName)
      
      Console.WriteLine("Version: {0}", Environment.Version.ToString())
      
      Console.WriteLine("WorkingSet: {0}", Environment.WorkingSet)
      
      '  No example for Exit(exitCode) because doing so would terminate this example.

      '  <-- Keep this information secure! -->
      Dim query As [String] = "My system drive is %SystemDrive% and my" & _
                              " system root is %SystemRoot%"
      str = Environment.ExpandEnvironmentVariables(query)
      Console.WriteLine("ExpandEnvironmentVariables: {0}  {1}", nl, str)
      
      Console.WriteLine("GetEnvironmentVariable: {0}  My temporary directory is {1}.", _
                        nl, Environment.GetEnvironmentVariable("TEMP"))
      
      Console.WriteLine("GetEnvironmentVariables: ")
      Dim environmentVariables As IDictionary = Environment.GetEnvironmentVariables()
      Dim de As DictionaryEntry
      For Each de In environmentVariables
         Console.WriteLine("  {0} = {1}", de.Key, de.Value)
      Next de
      
      Console.WriteLine("GetFolderPath: {0}", _
              Environment.GetFolderPath(Environment.SpecialFolder.System))
      
      Dim drives As [String]() = Environment.GetLogicalDrives()
      Console.WriteLine("GetLogicalDrives: {0}", [String].Join(", ", drives))
   End Sub
End Class
'
'This example produces results similar to the following:
'(Any result that is lengthy or reveals information that should remain 
'secure has been omitted and marked "!---OMITTED---!".)
'
'C:\>env0 ARBITRARY TEXT
'
'-- Environment members --
'CommandLine: env0 ARBITRARY TEXT
'GetCommandLineArgs: env0, ARBITRARY, TEXT
'CurrentDirectory: C:\Documents and Settings\!---OMITTED---!
'ExitCode: 0
'HasShutdownStarted: False
'MachineName: !---OMITTED---!
'NewLine:
'  first line
'  second line
'  third line
'OSVersion: Microsoft Windows NT 5.1.2600.0
'StackTrace: '   at System.Environment.GetStackTrace(Exception e)
'   at System.Environment.GetStackTrace(Exception e)
'   at System.Environment.get_StackTrace()
'   at Sample.Main()'
'SystemDirectory: C:\WINNT\System32
'TickCount: 17995355
'UserDomainName: !---OMITTED---!
'UserInteractive: True
'UserName: !---OMITTED---!
'Version: !---OMITTED---!
'WorkingSet: 5038080
'ExpandEnvironmentVariables:
'  My system drive is C: and my system root is C:\WINNT
'GetEnvironmentVariable:
'  My temporary directory is C:\DOCUME~1\!---OMITTED---!\LOCALS~1\Temp.
'GetEnvironmentVariables: 
'  !---OMITTED---!
'GetFolderPath: C:\WINNT\System32
'GetLogicalDrives: A:\, C:\, D:\
'

Comentarios

Utilice la Environment clase para recuperar información como argumentos de la línea de comandos, el código de salida, la configuración de las variables de entorno, el contenido de la pila de llamadas, la hora desde el último arranque del sistema y la versión de la Common Language Runtime.Use the Environment class to retrieve information such as command-line arguments, the exit code, environment variable settings, contents of the call stack, time since last system boot, and the version of the common language runtime.

Propiedades

CommandLine CommandLine CommandLine CommandLine

Obtiene la línea de comandos para este proceso.Gets the command line for this process.

CurrentDirectory CurrentDirectory CurrentDirectory CurrentDirectory

Obtiene o establece la ruta de acceso completa del directorio de trabajo actual.Gets or sets the fully qualified path of the current working directory.

CurrentManagedThreadId CurrentManagedThreadId CurrentManagedThreadId CurrentManagedThreadId

Obtiene un identificador único para el actual subproceso administrado.Gets a unique identifier for the current managed thread.

ExitCode ExitCode ExitCode ExitCode

Obtiene o establece el código de salida del proceso.Gets or sets the exit code of the process.

HasShutdownStarted HasShutdownStarted HasShutdownStarted HasShutdownStarted

Obtiene un valor que indica si el dominio de aplicación actual se está descargando o si Common Language Runtime (CLR) se está cerrando.Gets a value that indicates whether the current application domain is being unloaded or the common language runtime (CLR) is shutting down.

Is64BitOperatingSystem Is64BitOperatingSystem Is64BitOperatingSystem Is64BitOperatingSystem

Determina si el sistema operativo actual es un sistema operativo de 64 bits.Determines whether the current operating system is a 64-bit operating system.

Is64BitProcess Is64BitProcess Is64BitProcess Is64BitProcess

Determina si el proceso actual es un proceso de 64 bits.Determines whether the current process is a 64-bit process.

MachineName MachineName MachineName MachineName

Obtiene el nombre NetBIOS del equipo local.Gets the NetBIOS name of this local computer.

NewLine NewLine NewLine NewLine

Obtiene la cadena de nueva línea definida para este entorno.Gets the newline string defined for this environment.

OSVersion OSVersion OSVersion OSVersion

Obtiene un objeto OperatingSystem que contiene el identificador de la plataforma actual y el número de versión.Gets an OperatingSystem object that contains the current platform identifier and version number.

ProcessorCount ProcessorCount ProcessorCount ProcessorCount

Obtiene el número de procesadores de la máquina actual.Gets the number of processors on the current machine.

StackTrace StackTrace StackTrace StackTrace

Obtiene información de seguimiento de la pila actual.Gets current stack trace information.

SystemDirectory SystemDirectory SystemDirectory SystemDirectory

Obtiene la ruta de acceso completa del directorio del sistema.Gets the fully qualified path of the system directory.

SystemPageSize SystemPageSize SystemPageSize SystemPageSize

Obtiene el número de bytes de la página de memoria del sistema operativo.Gets the number of bytes in the operating system's memory page.

TickCount TickCount TickCount TickCount

Obtiene el número de milisegundos transcurridos desde que se inició el sistema.Gets the number of milliseconds elapsed since the system started.

TickCount64 TickCount64 TickCount64 TickCount64

Obtiene el número de milisegundos transcurridos desde que se inició el sistema.Gets the number of milliseconds elapsed since the system started.

UserDomainName UserDomainName UserDomainName UserDomainName

Obtiene el nombre de dominio de red asociado al usuario actual.Gets the network domain name associated with the current user.

UserInteractive UserInteractive UserInteractive UserInteractive

Obtiene un valor que indica si el proceso actual se ejecuta en modo de interacción con el usuario.Gets a value indicating whether the current process is running in user interactive mode.

UserName UserName UserName UserName

Obtiene el nombre de usuario de la persona que inició sesión en el sistema operativo.Gets the user name of the person who is currently logged on to the operating system.

Version Version Version Version

Obtiene un objeto Version que describe los números principal, secundario, de compilación y de revisión de Common Language Runtime.Gets a Version object that describes the major, minor, build, and revision numbers of the common language runtime.

WorkingSet WorkingSet WorkingSet WorkingSet

Obtiene la cantidad de memoria física asignada al contexto del proceso.Gets the amount of physical memory mapped to the process context.

Métodos

Exit(Int32) Exit(Int32) Exit(Int32) Exit(Int32)

Termina este proceso y devuelve un código de salida al sistema operativo.Terminates this process and returns an exit code to the operating system.

ExpandEnvironmentVariables(String) ExpandEnvironmentVariables(String) ExpandEnvironmentVariables(String) ExpandEnvironmentVariables(String)

Reemplaza el nombre de cada variable de entorno incluida en la cadena especificada por la cadena equivalente del valor de la variable y devuelve la cadena resultante.Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.

FailFast(String) FailFast(String) FailFast(String) FailFast(String)

Finaliza inmediatamente un proceso después de escribir un mensaje en el registro de eventos de la aplicación Windows y, después, incluye el mensaje en el informe de errores que se envía a Microsoft.Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message in error reporting to Microsoft.

FailFast(String, Exception) FailFast(String, Exception) FailFast(String, Exception) FailFast(String, Exception)

Finaliza inmediatamente un proceso después de escribir un mensaje en el registro de eventos de la aplicación Windows y, luego, incluye el mensaje y la información de excepción en el informe de errores que se envía a Microsoft.Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message and exception information in error reporting to Microsoft.

GetCommandLineArgs() GetCommandLineArgs() GetCommandLineArgs() GetCommandLineArgs()

Devuelve una matriz de cadena que contiene los argumentos de la línea de comandos del proceso actual.Returns a string array containing the command-line arguments for the current process.

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

Recupera el valor de una variable de entorno del proceso actual.Retrieves the value of an environment variable from the current process.

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

Recupera el valor de una variable de entorno del proceso actual o de la clave del Registro del sistema operativo Windows para la máquina local o el usuario actual.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.

GetEnvironmentVariables() GetEnvironmentVariables() GetEnvironmentVariables() GetEnvironmentVariables()

Recupera todos los nombres de las variables de entorno y sus valores del proceso actual.Retrieves all environment variable names and their values from the current process.

GetEnvironmentVariables(EnvironmentVariableTarget) GetEnvironmentVariables(EnvironmentVariableTarget) GetEnvironmentVariables(EnvironmentVariableTarget) 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.Retrieves all environment variable names and their values from the current process, or from the Windows operating system registry key for the current user or local machine.

GetFolderPath(Environment+SpecialFolder) GetFolderPath(Environment+SpecialFolder) GetFolderPath(Environment+SpecialFolder) GetFolderPath(Environment+SpecialFolder)

Obtiene la ruta de acceso a la carpeta especial del sistema identificada por la enumeración especificada.Gets the path to the system special folder that is identified by the specified enumeration.

GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption) GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption) GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption) GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption)

Obtiene la ruta de acceso a la carpeta especial del sistema identificada por la enumeración especificada y usa una opción especificada para tener acceso a carpetas especiales.Gets the path to the system special folder that is identified by the specified enumeration, and uses a specified option for accessing special folders.

GetLogicalDrives() GetLogicalDrives() GetLogicalDrives() GetLogicalDrives()

Devuelve una matriz de cadena que contiene los nombres de las unidades lógicas del equipo actual.Returns an array of string containing the names of the logical drives on the current computer.

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

Crea, modifica o elimina una variable de entorno almacenada en el proceso actual.Creates, modifies, or deletes an environment variable stored in the current process.

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

Crea, modifica o elimina una variable de entorno almacenada en el proceso actual o en la clave del Registro del sistema operativo Windows reservada para la máquina local o el usuario actual.Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.

Se aplica a