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 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 |
Возвращает командную строку для этого процесса. |
| CpuUsage |
Получите использование ЦП, включая время процесса, затраченное на выполнение кода приложения, время процесса, затраченное на выполнение кода операционной системы, и общее время, затраченное на выполнение кода приложения и операционной системы. |
| CurrentDirectory |
Возвращает или задает полный путь текущего рабочего каталога. |
| CurrentManagedThreadId |
Возвращает уникальный идентификатор текущего управляемого потока. |
| ExitCode |
Возвращает или задает код выхода процесса. |
| HasShutdownStarted |
Возвращает значение, указывающее, выгружается ли текущий домен приложения или среда CLR завершает работу. |
| Is64BitOperatingSystem |
Возвращает значение, указывающее, является ли текущая операционная система 64-разрядной операционной системой. |
| Is64BitProcess |
Возвращает значение, указывающее, является ли текущий процесс 64-разрядным процессом. |
| IsPrivilegedProcess |
Возвращает значение, указывающее, разрешен ли текущий процесс выполнять функции, относящиеся к безопасности. |
| MachineName |
Возвращает имя NetBIOS этого локального компьютера. |
| NewLine |
Возвращает строку новой строки, определенную для этой среды. |
| OSVersion |
Возвращает текущий идентификатор платформы и номер версии. |
| ProcessId |
Возвращает уникальный идентификатор текущего процесса. |
| ProcessorCount |
Возвращает количество процессоров, доступных для текущего процесса. |
| ProcessPath |
Возвращает путь исполняемого файла, запускающего текущий процесс. Возвращает, |
| StackTrace |
Возвращает текущие сведения трассировки стека. |
| SystemDirectory |
Возвращает полный путь системного каталога. |
| SystemPageSize |
Возвращает количество байтов на странице памяти операционной системы. |
| TickCount |
Возвращает количество миллисекундах, истекшее с момента запуска системы. |
| TickCount64 |
Возвращает количество миллисекундах, истекшее с момента запуска системы. |
| UserDomainName |
Возвращает сетевое доменное имя, связанное с текущим пользователем. |
| UserInteractive |
Возвращает значение, указывающее, выполняется ли текущий процесс в интерактивном режиме пользователя. |
| UserName |
Возвращает имя пользователя, связанного с текущим потоком. |
| Version |
Получает версию, состоящую из основных, дополнительных, сборок и номеров редакций среды CLR. |
| WorkingSet |
Возвращает объем физической памяти, сопоставленной с контекстом процесса. |
Методы
| Имя | Описание |
|---|---|
| Exit(Int32) |
Завершает этот процесс и возвращает код выхода в операционную систему. |
| ExpandEnvironmentVariables(String) |
Заменяет имя каждой переменной среды, внедренной в указанную строку, строковым эквивалентом значения переменной, а затем возвращает результирующая строка. |
| FailFast(String, Exception) |
Немедленно завершает процесс перед сообщением об ошибке. Для Windows сообщение об ошибке записывается в журнал событий приложения Windows, а сведения об ошибке и сведения об исключении включены в отчеты об ошибках Microsoft. Для таких систем Unix сообщение вместе с трассировкой стека записывается в стандартный поток ошибок. |
| FailFast(String) |
Немедленно завершает процесс перед сообщением об ошибке. Для Windows сообщение об ошибке записывается в журнал событий приложения Windows, а сообщение включается в отчет об ошибках Microsoft. Для систем, таких как Unix, сообщение, наряду с трассировкой стека, записывается в стандартный поток ошибок. |
| GetCommandLineArgs() |
Возвращает строковый массив, содержащий аргументы командной строки для текущего процесса. |
| GetEnvironmentVariable(String, EnvironmentVariableTarget) |
Извлекает значение переменной среды из текущего процесса или из раздела реестра операционной системы Windows текущего пользователя или локального компьютера. |
| GetEnvironmentVariable(String) |
Извлекает значение переменной среды из текущего процесса. |
| GetEnvironmentVariables() |
Извлекает все имена переменных среды и их значения из текущего процесса. |
| GetEnvironmentVariables(EnvironmentVariableTarget) |
Извлекает все имена переменных среды и их значения из текущего процесса или из раздела реестра операционной системы Windows для текущего пользователя или локального компьютера. |
| GetFolderPath(Environment+SpecialFolder, Environment+SpecialFolderOption) |
Возвращает путь к указанной системе специальной папке с помощью указанного параметра для доступа к специальным папкам. |
| GetFolderPath(Environment+SpecialFolder) |
Возвращает путь к указанной системе специальной папке. |
| GetLogicalDrives() |
Извлекает имена логических дисков на этом компьютере. |
| SetEnvironmentVariable(String, String, EnvironmentVariableTarget) |
Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе или в разделе реестра операционной системы Windows, зарезервированном для текущего пользователя или локального компьютера. |
| SetEnvironmentVariable(String, String) |
Создает, изменяет или удаляет переменную среды, хранящуюся в текущем процессе. |