Environment Класс

Определение

Предоставляет сведения о текущей среде и платформе, а также необходимые для управления ими средства. Этот класс не наследуется.

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
Наследование
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
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:\
'

Комментарии

Environment Используйте класс для получения таких сведений, как аргументы командной строки, код выхода, параметры переменных среды, содержимое стека вызовов, время с момента последней загрузки системы и версия среды CLR.

Свойства

CommandLine

Возвращает командную строку для данного процесса.

CurrentDirectory

Возвращает или задает полный путь к текущей рабочей папке.

CurrentManagedThreadId

Возвращает уникальный идентификатор текущего управляемого потока.

ExitCode

Возвращает или задает код выхода из процесса.

HasShutdownStarted

Возвращает значение, указывающее, выгружается ли текущий домен приложения или среда CLR завершает работу.

Is64BitOperatingSystem

Возвращает значение, указывающее, является ли текущая операционная система 64-разрядной.

Is64BitProcess

Возвращает значение, указывающее, является ли текущий процесс 64-разрядным.

IsPrivilegedProcess

Возвращает значение, указывающее, авторизован ли текущий процесс для выполнения функций, связанных с безопасностью.

MachineName

Возвращает имя NetBIOS данного локального компьютера.

NewLine

Возвращает строку, обозначающую в данной среде начало новой строки.

OSVersion

Возвращает идентификатор текущей платформы и номер версии.

ProcessId

Возвращает уникальный идентификатор текущего процесса.

ProcessorCount

Возвращает количество процессоров, доступных для текущего процесса.

ProcessPath

Возвращает путь к исполняемому файлу, который запустил текущий выполняемый процесс. Возвращает, null если путь недоступен.

StackTrace

Возвращает текущие сведения о трассировке стека.

SystemDirectory

Возвращает полный путь к системному каталогу.

SystemPageSize

Возвращает количество байтов на странице памяти операционной системы.

TickCount

Возвращает время, истекшее с момента загрузки системы (в миллисекундах).

TickCount64

Возвращает время, истекшее с момента загрузки системы (в миллисекундах).

UserDomainName

Возвращает имя сетевого домена, связанное с текущим пользователем.

UserInteractive

Возвращает значение, позволяющее определить, выполняется ли текущий процесс в режиме взаимодействия с пользователем.

UserName

Возвращает имя пользователя, сопоставленное с текущим потоком.

Version

Возвращает версию, состоящую из основных, дополнительных номеров, номеров сборки и редакции среды CLR.

WorkingSet

Возвращает объем физической памяти, сопоставленной контексту процесса.

Методы

Exit(Int32)

Завершает этот процесс и возвращает код выхода операционной системе.

ExpandEnvironmentVariables(String)

Замещает имя каждой переменной среды, внедренной в указанную строку, строчным эквивалентом значения переменной, а затем возвращает результирующую строку.

FailFast(String)

Немедленно завершает процесс перед сообщением об ошибке. Для Windows сообщение об ошибке записывается в журнал событий приложения Windows и включается в отчеты об ошибках в корпорацию Майкрософт. Для unix-подобных систем сообщение вместе с трассировкой стека записывается в стандартный поток ошибок.

FailFast(String, Exception)

Немедленно завершает процесс перед сообщением об ошибке. Для Windows сообщение об ошибке записывается в журнал событий приложения Windows, а сообщение и сведения об исключении включаются в отчеты об ошибках в Корпорацию Майкрософт. Для unix-подобных систем сообщение вместе с трассировкой стека записывается в стандартный поток ошибок.

GetCommandLineArgs()

Возвращает строковый массив, содержащий аргументы командной строки для текущего процесса.

GetEnvironmentVariable(String)

Возвращает из текущего процесса значение переменной среды.

GetEnvironmentVariable(String, EnvironmentVariableTarget)

Возвращает из текущего процесса или раздела реестра операционной системы Windows значение переменной среды для текущего пользователя или локального компьютера.

GetEnvironmentVariables()

Возвращает из текущего процесса имена всех переменных среды и их значения.

GetEnvironmentVariables(EnvironmentVariableTarget)

Возвращает из текущего процесса или раздела реестра операционной системы Windows имена и значения всех переменных среды для текущего пользователя или локального компьютера.

GetFolderPath(Environment+SpecialFolder)

Возвращает путь к указанной системной специальной папке.

GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption)

Возвращает путь к указанной системной специальной папке с помощью указанного параметра для доступа к специальным папкам.

GetLogicalDrives()

Возвращает массив строк, содержащий имена логических дисков текущего компьютера.

SetEnvironmentVariable(String, String)

Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе.

SetEnvironmentVariable(String, String, EnvironmentVariableTarget)

Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе или разделе реестра операционной системы Windows, зарезервированном для текущего пользователя или локального компьютера.

Применяется к