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?
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
OSVersion: This property returns the operating system version in
OperatingSystem class object. The
OperatingSystemclass has three properties,
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
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
GetSystemInormation Win32 APIs to extract this kind of
Version: This property returns the Version class object for current assembly.
ExitCode: This is property equivalent to Win32 APIs
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
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
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
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
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
GetLogicalDrives Win32 API.
Exit: This method terminates the calling process. This is equivalent to use of
exit function in
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
All these members of
Environment class can be used as follows.
string strSysFolder = Environment.SystemDirectory;
string strCurFolder = Environment.CurrentDirectory;
string strCmdLine = Environment.CommandLine;
string strArgs = Environment.GetCommandLineArgs();
string strNewLine = Environment.NewLine;
Version vs = Environment.Version;
string strStack = Environment.StackTrace;
int nTicks = Environment.TickCount;
char chPathSep = Environment.PathSeparator;
char chDirSep = Environment.DirectorySeparatorChar;
char chVolSep = Environment.VolumeSeparatorChar;
char chAltDirSep = Environment.AltDirectorySeparatorChar;
char  chInvalidInPath = Environment.InvalidPathChars;
string strInvalidChars = "";
for (int i = 0; i < chInvalidInPath.Length; i++)
strInvalidChars += chInvalidInPath[i];
string  strVal = Environment.GetLogicalDrives ();
string strDrives = "";
for (int i = 0; i < strVal.Length; i++)
strDrives += strVal[i];
if (i < strVal.Length -1 )
strDrives += ",";
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
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
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
Path Separator: ;
Directory Separator: \
Alt Directory Separator: /
Volume Separator: :
Invalid Characters In Path: "<|
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\
CommonProgramFiles: C:\Program Files\Common Files
MSSdk: C:\Program Files\Microsoft Platform SDK\
Assembly Version: 1.0.2204.21
Stack Trace: at System.Environment.GetStackTrace(Exception e)
at ConsoleTesApp.ConsoleTestApp.Main(String args)