Publish Article

How to Use System.Environment class to get your environment

As the title of article says, I will be discussing the use of System.Environment class in the System namespace. I was looking for equivalents to some of very useful Win32 APIs that we use in our projects a lot. For example: What is my OS, what is the path to the system folder, what is the current folder, how do I terminate a process, etc? In Win32 we have APIs like GetVersionEx, GetSystemDirectory, GetCurrentDirectory, etc. to accomplish all these tasks. So where do we look in .NET SDK for all these APIs?

System.Environment class

It's the Environment class under System namespace that provides the equivalent methods and properties that we can use to get these values. The Environment class exposes following properties to extract the information we want.

  • OSVersion: This property returns the operating system version in OperatingSystem class object. The OperatingSystemclass has three properties, CSD, PlatformID and Version that gives the values of Service Pack, Platform Type (WinNT, Win9x or Win32s) and Version (Major, Minor, Revision and Build number). This property is equivalent to GetVersionEx API.
  • SystemDirectory: This property is equivalent GetSystemDirectory Win32 API. It returns the complete path to system folder.
  • CurrentDirectory: This property is equivalent to GetCurrentDirectory Win32 API. This returns the complete path to folder from where current process is running.
  • CommandLine: This property is equivalent to GetCommandLine Win32 API. This returns the command-line string for the current process.
  • NewLine: This property returns the new line string for the given platform.
  • Ticks: This property returns the number of milliseconds since it was started. This is equivalent to GetTickCount Win32 API.
  • WorkingSet: This property returns the amount of physical memory mapped to the process context. This is equivalent to use of VirtualQuery, GetSystemInormation Win32 APIs to extract this kind of information.
  • Version: This property returns the Version class object for current assembly.
  • ExitCode: This is property equivalent to Win32 APIs GetProcessExitCode, GetThreadExitCode etc. It can be used to set and get the exit code of a process.
  • StackTrace: There is no direct equivalent on Win32 SDK for this property. This property returns string representation of current stack trace. In Win32 you could use StackWalk to obtain the stack trace. And then interpret the stack frame to get the line numbers and name of functions in the stack. .NET has made it simple to get the stack for the current process.

Environment class also exposes some very useful fields that give the information about the characters used for directory separators, path separators, volume separators, etc.

  • PathSeparator: This field provides path separator character. E.g. ";" on Windows and this is also the default value.
  • DirectorySeparatorChar: This field provides directory separator character. E.g. "\" on Windows, "/" on Unix, and ":" on Mac operating systems.
  • AltDirectorySeparatorChar: This field provides alternate directory separator character. E.g. "\" on Unix, and "/" on Windows and Mac operating systems.
  • VolumeSeparatorChar: This field provides volume separator character. E.g. It is colon ":" on Windows and Macintosh, and "/" on Unix operating systems. This is mostly useful for parsing paths like "c:\windows" or "MacVolume:System Folder".
  • InvalidPathChars: This field provides list of invalid characters in a path. E.g. on windows it returns a list of four characters "<|.

And at the end, Environment class also has couple of very useful methods too. That can be used to extract information like environment variables currently set, command line arguments, value of a particular environment variable etc.

  • GetCommandLineArgs: This method returns an array of strings containing the command line arguments passed for starting the process. Please do read the documentation to see what is behavior on different platforms. This functionality is similar to CommandLineToArgvW usage of Win32 API.
  • GetEnvironmentVariables: This method returns an IDictionary object containing the values of all the environment variables that are set for the system. Get the IDictionaryEnumerator from the returned IDictionary object to get list of values of each environment variable. This is the same list you get when you type "set" command at dos prompt. This is equivalent to GetEnvironmentStrings Win32 API.
  • GetEnvironmentVariable: This method returns value of a specific environment variable you ask for. This is equivalent to GetEnvironmentVariable Win32 API.
  • GetLogicalDrives: This method returns an array of strings containing the string values for each logical drive installed on a system. E.g. on my machine this string looks like A:\C:\D:\E:\F:\G:\H:\I:\J:\K:\L:\. This method is equivalent to GetLogicalDrives Win32 API.
  • Exit: This method terminates the calling process. This is equivalent to use of exit function in CRT.
  • ExpandEnvironmentVariables: This method expands environment-variable strings and replaces them with their defined values. E.g. a value like %PATH% gets expanded to value actually representing the path i.e. some thing like c:\winnt\system32.

All these members of Environment class can be used as follows.

// 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";

Look at the ConsoleTestApp.cs file in the project attached with this article for more detailed implementation. Detection of operating system is implemented in NKOSInfo class in NKDiagnosticUtility project.

I logged the results of all the calls to the Environment class members in a text file. The output on my machine is as follows. I have deleted some of the verbose information like PATH, INCLUDE, LIB etc. to save space.

Operating System: Windows 2000
Service Pack: Service Pack 1
Major Version: 5
Minor Version: 0
Revision: 0
Build: 2195

Logical Drives: A:\,C:\,D:\,E:\,F:\,G:\,H:\,I:\,J:\,K:\,L:\
System Running Since: 1546719324 secs
System Directory: C:\WINNT\System32
Current Directory: H:\NetProjects\DiagnosticSrvcs\bin\Debug
Commnad Line: ConsoleTesApp
Commnad Line Args: ConsoleTesApp

New Line:
Path Separator: ;
Directory Separator: \
Alt Directory Separator: /
Volume Separator: :
Invalid Characters In Path: "<|

------------Environment Variables-----------------
DDKROOT: H:\Program Files\NTDDK
INETSDK: C:\Program Files\Microsoft Platform SDK\
ALLUSERSPROFILE: C:\Documents and Settings\All Users
VSCOMNTOOLS: "H:\Program Files\Microsoft Visual Studio.NET\Common7\Tools\"
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
Windows_NT SystemDrive: C:
MSSdk: C:\Program Files\Microsoft Platform SDK\
windir: C:\WINNT
Cor_Enable_Profiling: 0
SystemRoot: C:\WINNT

Assembly Version: 1.0.2204.21
Stack Trace: at System.Environment.GetStackTrace(Exception e)
at System.Environment.get_StackTrace()
at ConsoleTesApp.ConsoleTestApp.Main(String[] args)

Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix