Partilhar via


Environment Classe

Definição

Fornece informações sobre e significa que para manipular, o ambiente atual e a plataforma. Essa classe não pode ser herdada.

public ref class Environment abstract sealed
public ref class Environment sealed
public static class Environment
public sealed class Environment
[System.Runtime.InteropServices.ComVisible(true)]
public static class Environment
type Environment = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type Environment = class
Public Class Environment
Public NotInheritable Class Environment
Herança
Environment
Atributos

Exemplos

O exemplo a seguir exibe uma lista de informações sobre o ambiente atual.

// 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
open System
open System.Collections

let nl = Environment.NewLine

printfn ""
printfn "-- Environment members --"

//  Invoke this sample with an arbitrary set of command line arguments.
printfn $"CommandLine: {Environment.CommandLine}"

Environment.GetCommandLineArgs()
|> String.concat ", "
|> printfn "GetCommandLineArgs: %s"

//  <-- Keep this information secure! -->
printfn $"CurrentDirectory: {Environment.CurrentDirectory}"

printfn $"ExitCode: {Environment.ExitCode}"

printfn $"HasShutdownStarted: {Environment.HasShutdownStarted}"

//  <-- Keep this information secure! -->
printfn $"MachineName: {Environment.MachineName}"

printfn $"NewLine: {nl}  first line{nl}  second line{nl}  third line"

printfn $"OSVersion: {Environment.OSVersion}"

printfn $"StackTrace: '{Environment.StackTrace}'"

//  <-- Keep this information secure! -->
printfn $"SystemDirectory: {Environment.SystemDirectory}"

printfn $"TickCount: {Environment.TickCount}"

//  <-- Keep this information secure! -->
printfn $"UserDomainName: {Environment.UserDomainName}"

printfn $"UserInteractive: {Environment.UserInteractive}"

//  <-- Keep this information secure! -->
printfn $"UserName: {Environment.UserName}"

printfn $"Version: {Environment.Version}"

printfn $"WorkingSet: {Environment.WorkingSet}"

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

//  <-- Keep this information secure! -->
let query = "My system drive is %SystemDrive% and my system root is %SystemRoot%"
let str = Environment.ExpandEnvironmentVariables query
printfn $"ExpandEnvironmentVariables: {nl}  {str}"

printfn $"""GetEnvironmentVariable: {nl}  My temporary directory is {Environment.GetEnvironmentVariable "TEMP"}."""

printfn "GetEnvironmentVariables: "
let environmentVariables = Environment.GetEnvironmentVariables()
for de in environmentVariables do
    let de = de :?> DictionaryEntry
    printfn $"  {de.Key} = {de.Value}"

printfn $"GetFolderPath: {Environment.GetFolderPath Environment.SpecialFolder.System}"

Environment.GetLogicalDrives()
|> String.concat ", "
|> printfn "GetLogicalDrives: %s"

// 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:\
'

Comentários

Use a Environment classe para recuperar informações como argumentos de linha de comando, código de saída, configurações de variável de ambiente, conteúdo da pilha de chamadas, tempo desde a última inicialização do sistema e a versão do common language runtime.

Propriedades

CommandLine

Obtém a linha de comando para esse processo.

CpuUsage

Fornece informações sobre e significa que para manipular, o ambiente atual e a plataforma. Essa classe não pode ser herdada.

CurrentDirectory

Obtém ou define o caminho totalmente qualificado do diretório de trabalho atual.

CurrentManagedThreadId

Obtém um identificador exclusivo para o thread gerenciado atual.

ExitCode

Obtém ou define o código de saída do processo.

HasShutdownStarted

Obtém um valor que indica se o domínio de aplicativo atual está sendo descarregado ou o se o CLR (Common Language Runtime) está sendo desligado.

Is64BitOperatingSystem

Obtém um valor que indica se o sistema operacional atual é um sistema operacional de 64 bits.

Is64BitProcess

Obtém um valor que indica se o processo atual é um processo de 64 bits.

IsPrivilegedProcess

Obtém um valor que indica se o processo atual está autorizado a executar funções relevantes à segurança.

MachineName

Obtém o nome NetBIOS deste computador local.

NewLine

Obtém a cadeia de caracteres de nova linha definida para esse ambiente.

OSVersion

Obtém o identificador de plataforma atual e o número de versão.

ProcessId

Obtém o identificador exclusivo para o processo atual.

ProcessorCount

Obtém o número de processadores disponíveis para o processo atual.

ProcessPath

Retorna o caminho do executável que iniciou o processo em execução no momento. Retorna null quando o caminho não está disponível.

StackTrace

Obtém informações do rastreamento de pilha atual.

SystemDirectory

Obtém o caminho totalmente qualificado do diretório do sistema.

SystemPageSize

Obtém o número de bytes na página de memória do sistema operacional.

TickCount

Obtém o número de milissegundos decorridos desde a inicialização do sistema.

TickCount64

Obtém o número de milissegundos decorridos desde a inicialização do sistema.

UserDomainName

Obtém o nome de domínio de rede associado ao usuário atual.

UserInteractive

Obtém um valor que indica se o processo atual está em execução no modo de interação com o usuário.

UserName

Obtém o nome de usuário da pessoa que está associada ao segmento atual.

Version

Obtém uma versão que consiste nos números principal, secundário, de build e de revisão do Common Language Runtime.

WorkingSet

Obtém a quantidade de memória física mapeada para o contexto do processo.

Métodos

Exit(Int32)

Encerra esse processo e retorna um código de saída para o sistema operacional.

ExpandEnvironmentVariables(String)

Substitui o nome de cada variável de ambiente inserida na cadeia de caracteres especificada com o equivalente de cadeia de caracteres do valor da variável e, em seguida, retorna a cadeia de caracteres resultante.

FailFast(String)

Encerra imediatamente o processo antes de relatar uma mensagem de erro. Para o Windows, a mensagem de erro é gravada no log de eventos do Aplicativo windows e a mensagem é incluída no relatório de erros para a Microsoft. Para sistemas semelhantes ao Unix, a mensagem, juntamente com o rastreamento de pilha, é gravada no fluxo de erros padrão.

FailFast(String, Exception)

Encerra imediatamente o processo antes de relatar uma mensagem de erro. Para o Windows, a mensagem de erro é gravada no log de eventos do Aplicativo windows e as informações de mensagem e exceção são incluídas no relatório de erros para a Microsoft. Para sistemas semelhantes ao Unix, a mensagem junto com o rastreamento de pilha é gravada no fluxo de erro padrão.

GetCommandLineArgs()

Retorna uma matriz de cadeia de caracteres que contém os argumentos de linha de comando para o processo atual.

GetEnvironmentVariable(String)

Recupera o valor de uma variável de ambiente do processo atual.

GetEnvironmentVariable(String, EnvironmentVariableTarget)

Recupera o valor de uma variável de ambiente do processo atual ou da chave do Registro do sistema operacional Windows para o usuário atual ou o computador local.

GetEnvironmentVariables()

Recupera todos os nomes de variáveis de ambiente e seus valores do processo atual.

GetEnvironmentVariables(EnvironmentVariableTarget)

Recupera todos os nomes de variáveis de ambiente e seus valores do processo atual ou de uma chave do Registro do sistema operacional Windows para o usuário atual ou o computador local.

GetFolderPath(Environment+SpecialFolder)

Obtém o caminho para a pasta especial do sistema especificada.

GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption)

Obtém o caminho para a pasta especial do sistema especificada usando uma opção especificada para acessar pastas especiais.

GetLogicalDrives()

Retorna uma matriz de cadeia de caracteres que contém os nomes das unidades lógicas no computador atual.

SetEnvironmentVariable(String, String)

Cria, modifica ou exclui uma variável de ambiente armazenada no processo atual.

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

Cria, modifica ou exclui uma variável de ambiente armazenada no processo atual ou na chave do Registro do sistema operacional Windows reservada para o usuário atual ou o computador local.

Aplica-se a