65.9K
CodeProject 正在变化。 阅读更多。
Home

.NET 诊断 – IV,使用 Environment 类获取你的环境

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (8投票s)

2001 年 3 月 20 日

viewsIcon

94743

downloadIcon

520

解释了 Environment 类的使用,以提取操作系统、环境变量等信息。

引言

正如文章标题所示,我将讨论 `System` 命名空间下 `Environment` 类的用法。我一直在寻找一些在我们的项目中经常使用的非常重要的 Win32 API 的等价物。例如:我的操作系统是什么,系统文件夹的路径是什么,当前文件夹是什么,如何终止进程等等?在 Win32 中,我们有 `GetVersionEx`、`GetSystemDirectory`、`GetCurrentDirectory` 等 API 来完成所有这些任务。那么,我们在 .NET SDK 中哪里可以找到所有这些 API 呢?

Environment 类

`System` 命名空间下的 `Environment` 类提供了等价的方法和属性,我们可以用它们来获取这些值。`Environment` 类公开了以下属性来提取我们想要的信息。

  • OSVersion:此属性以 `OperatingSystem` 类对象的形式返回操作系统版本。`OperatingSystem` 类有三个属性:`CSD`、`PlatformID` 和 `Version`,分别提供服务包、平台类型(WinNT、Win9x 或 Win32s)和版本(主版本、次版本、修订号和内部版本号)的值。此属性等同于 `GetVersionEx` API。
  • SystemDirectory:此属性等同于 `GetSystemDirectory` Win32 API。它返回系统文件夹的完整路径。
  • CurrentDirectory:此属性等同于 `GetCurrentDirectory` Win32 API。它返回当前进程运行所在文件夹的完整路径。
  • CommandLine:此属性等同于 `GetCommandLine` Win32 API。它返回当前进程的命令行字符串。
  • NewLine:此属性返回给定平台的换行符字符串。
  • Ticks:此属性返回自启动以来的毫秒数。这等同于 `GetTickCount` Win32 API。
  • WorkingSet:此属性返回映射到进程上下文的物理内存量。这等同于使用 `VirtualQuery`、`GetSystemInormation` Win32 API 来提取此类信息。
  • Version:此属性返回当前程序集的 Version 类对象。
  • ExitCode:此属性等同于 Win32 API `GetProcessExitCode`、`GetThreadExitCode` 等。它可以用于设置和获取进程的退出代码。
  • StackTrace:Win32 SDK 中没有此属性的直接等价物。此属性返回当前堆栈跟踪的字符串表示形式。在 Win32 中,您可以使用 `StackWalk` 来获取堆栈跟踪。然后解释堆栈帧以获取堆栈中的行号和函数名。.NET 已简化了获取当前进程堆栈的操作。

Environment 类还公开了一些非常有用的字段,它们提供了有关用作目录分隔符、路径分隔符、卷分隔符等的字符的信息。

  • PathSeparator:此字段提供路径分隔符。例如,Windows 上的 ";",这也是默认值。
  • DirectorySeparatorChar:此字段提供目录分隔符。例如,Windows 上的 "\",Unix 上的 "/",Mac 操作系统上的 ":"。
  • AltDirectorySeparatorChar:此字段提供备用目录分隔符。例如,Unix 上的 "\",Windows 和 Mac 操作系统上的 "/"。
  • VolumeSeparatorChar:此字段提供卷分隔符。例如,在 Windows 和 Macintosh 上是冒号 ":",在 Unix 操作系统上是 "/"。这对于解析像 "c:\windows" 或 "MacVolume:System Folder" 这样的路径非常有用。
  • InvalidPathChars:此字段提供路径中无效字符的列表。例如,在 Windows 上,它返回四个字符的列表:<|。

最后,`Environment` 类还有几个非常有用的方法。它们可用于提取当前设置的环境变量、命令行参数、特定环境变量的值等信息。

  • GetCommandLineArgs:此方法返回一个字符串数组,其中包含启动进程时传递的命令行参数。请阅读文档以了解其在不同平台上的行为。此功能类似于 Win32 API 的 `CommandLineToArgvW` 用法。
  • GetEnvironmentVariables:此方法返回一个 `IDictionary` 对象,其中包含为系统设置的所有环境变量的值。从返回的 `IDictionary` 对象获取 `IDictionaryEnumerator` 以获取每个环境变量的值列表。这与您在 DOS 提示符下键入 "set" 命令时获得的列表相同。这等同于 `GetEnvironmentStrings` Win32 API。
  • GetEnvironmentVariable:此方法返回您请求的特定环境变量的值。这等同于 `GetEnvironmentVariable` Win32 API。
  • GetLogicalDrives:此方法返回一个字符串数组,其中包含系统上安装的每个逻辑驱动器的字符串值。例如,在我的机器上,这个字符串看起来像 A:\C:\D:\E:\F:\G:\H:\I:\J:\K:\L:\。此方法等同于 `GetLogicalDrives` Win32 API。
  • Exit:此方法终止调用进程。这等同于在 CRT 中使用 `exit` 函数。
  • ExpandEnvironmentVariables:此方法展开环境变量字符串并将其替换为定义的值。例如,像 %PATH% 这样的值将被展开为实际表示路径的值,即类似于 c:\winnt\system32 的内容。

`Environment` 类的所有这些成员都可以如下使用。

// Get the system folder where OS is installed.
string strSysFolder = Environment.SystemDirectory;

// Get the current folder where this app is runing from.
string strCurFolder = Environment.CurrentDirectory;

// Get the commnad line for this process.
string strCmdLine = Environment.CommandLine;

// Get the command line arguments.
string []strArgs = Environment.GetCommandLineArgs();

// Get the new line string used.
string strNewLine = Environment.NewLine;

// Get the version of current assembly.
Version vs = Environment.Version;

// Get the stack trace.
string strStack = Environment.StackTrace;

// Get the number of millisecnds since system was started.
int nTicks = Environment.TickCount;

// Get the platform specific path separator.
char chPathSep = Environment.PathSeparator;

// Get the platform specific director separator.
char chDirSep = Environment.DirectorySeparatorChar;

// Get the platform specific volume separator character.
char chVolSep = Environment.VolumeSeparatorChar;

// Get the platform-specific alternate directory 
// separator character
char chAltDirSep = Environment.AltDirectorySeparatorChar;

// Get the platform-specific list of invalid characters 
// in a path.
char [] chInvalidInPath = Environment.InvalidPathChars;
string strInvalidChars = "";

for (int i = 0; i < chInvalidInPath.Length; i++)
{
    strInvalidChars += chInvalidInPath[i];
}

// Get list of logical drives.
string [] strVal = Environment.GetLogicalDrives ();
string strDrives = "";

for (int i = 0; i < strVal.Length; i++)
{
    strDrives += strVal[i];
    
    if (i < strVal.Length -1 )
    {
        strDrives += ",";
    }
}

// Get all the environemt variables.
string strEnvVars = "";

IDictionary dict = Environment.GetEnvironmentVariables();

IDictionaryEnumerator dictEnum = dict.GetEnumerator();

while (true == dictEnum.MoveNext())
{
    DictionaryEntry dictEntry = dictEnum.Entry;

    strEnvVars += dictEntry.Key;

    strEnvVars += ": ";

    strEnvVars += dictEntry.Value;

    strEnvVars += "\n";
}

请查看本文附带项目中的 `ConsoleTestApp.cs` 文件以获取更详细的实现。操作系统检测在 `NKDiagnosticUtility` 项目的 `NKOSInfo` 类中实现。

我将 `Environment` 类所有成员的调用结果记录在一个文本文件中。我的机器上的输出如下。为了节省空间,我删除了一些冗长的信息,如 PATH、INCLUDE、LIB 等。

操作系统:Windows 2000
服务包:Service Pack 1
主版本:5
次版本:0
修订号:0
内部版本:2195

逻辑驱动器:A:\,C:\,D:\,E:\,F:\,G:\,H:\,I:\,J:\,K:\,L:\
系统运行时间:1546719324 秒
系统目录:C:\WINNT\System32
当前目录:H:\NetProjects\DiagnosticSrvcs\bin\Debug
命令行:ConsoleTesApp
命令行参数:ConsoleTesApp

换行符
路径分隔符:;
目录分隔符:\
备用目录分隔符:/
卷分隔符:
路径中的无效字符:<|

------------环境变量-----------------
PROCESSOR_ARCHITECTURE:x86
PROMPT:$P$G
PROCESSOR_REVISION:0806
DDKROOT:H:\Program Files\NTDDK
INETSDK:C:\Program Files\Microsoft Platform SDK\
ALLUSERSPROFILE:C:\Documents and Settings\All Users
PROCESSOR_LEVEL:6
VSCOMNTOOLS:"H:\Program Files\Microsoft Visual Studio.NET\Common7\Tools\"
netsdk:H:\PROGRA~1\MICROS~1.NET\FRAMEW~1\
Bkoffice:C:\Program Files\Microsoft Platform SDK\
PROCESSOR_IDENTIFIER:x86 Family 6 Model 8 Stepping 6, GenuineIntel
Mstools:C:\Program Files\Microsoft Platform SDK\
Os2LibPath:C:\WINNT\system32\os2\dll;
CommonProgramFiles:C:\Program Files\Common Files
HOMEPATH:\
OANOCACHE:1 OS
Windows_NT SystemDrive:C
NUMBER_OF_PROCESSORS:1
MSSdk:C:\Program Files\Microsoft Platform SDK\
windir:C:\WINNT
Cor_Enable_Profiling:0
SystemRoot:C:\WINNT
HOMEDRIVE:C

Assembly Version:1.0.2204.21
堆栈跟踪:at System.Environment.GetStackTrace(Exception e)
at System.Environment.get_StackTrace()
at ConsoleTesApp.ConsoleTestApp.Main(String[] args)

© . All rights reserved.