Home.NET Knowing Your Environment: the System.Envir...
Knowing Your Environment: the System.Environment Class
When developing applications (Windows or web), it is very important for the developer to know the environment in which the application is running. Having this information will help the developer customize the software and make the user experience more enjoyable. In this regard, .NET provides a class in the System namespace called Environment, which is the subject of this article.
Contributed by Ayad Boudiab Rating: / 2 May 12, 2008
The environment class contains methods and properties that provide information about the current environment and platform. It is important to note that this class cannot be inherited. In other words, you cannot extend the functionality in this class to create your own class.
Here is a rundown of some of the handy methods and properties that this class provides, with minor explanation on the usage of each.
Properties
CommandLine: The call to Environment.CommandLine will provide the full name of the application, followed by the command line arguments. The command line arguments are the pieces of data entered after the application name. For example:
Multiply.exe x1 x2
In this case, x1 and x2 are the command line arguments. In order to get access to x1 and x2, you use the args array passed to the Main method. Here is the method signature:
static void Main( string [] args)
Visual Studio provides two ways to enter the command line arguments:
By running the application from the command prompt.
By entering the arguments in the Debug tab of the project properties:
Here is a statement that shows how you access the CommandLine property:
//returns a string containing command-line arguments
Console .WriteLine( "The command line is: " + Environment .CommandLine);
CurrentDirectory : This property gets or sets the fully qualified path of the current working directory. Keep in mind that the current directory will contain a trailing slash if the process starts in the root directory. Otherwise, there will be no trailing slash. To print the current directory, use the following statement:
//returns a string containing a directory path
Console .WriteLine( "The directory path is: " + Environment .CurrentDirectory);
ExitCode : The result of this property is a 32-bit signed integer that contains the exit code of the process. Why would I need the exit code of the process? Glad you asked. The Main() method is the entry and exit points of an application. There are multiple versions of the Main() method. Our concern, however, is with the return type. Main() can return a void or an int. The int value reports to the calling program (probably a script) the status information. A 0 means that the program ran successfully. Other values means there are errors. However, how would you know the status when Main() returns void? The answer is: ExitCode. Just use the ExitCode property to get or set the exit code of the process:
//returns 0 by default, which means success!
Console .WriteLine( "The ExitCode is: " + Environment .ExitCode);
HasShutdownStarted: This property returns a Boolean value (true/false) to indicate whether the common language runtime is shutting down or the current application domain is unloading (in .NET, assemblies are not hosted directly in a process. They are hosted in an application domain). Use this property in an object's finalization method. If it returns true, then you cannot reliably access any object that has a finalization method and is referenced by a static field.
//returns a boolean value that indicates whether the common language runtime
//is shutting down or the application domain is unloading
Console .WriteLine( "Has shutdown started? {0}" ,
E nvironment .HasShutdownStarted);
MachineName: This property returns a string containing the name of the computer.
//returns a string containing the name of this computer
NewLine: Using this property results in a new line inserted in the string. You can use n, but in some platforms you might need rn. To be on the safe side, use Environment.NewLine consistently.
//A string containing "rn" for non-Unix platforms,
OSVersion: This property gets an OperatingSystem object that contains the current platform identifier and version number. Knowing the operating system version on which your application is running is extremely important; it helps you take advantage of some of the functionalities that exist in one version of the OS and not in another.
//Gets an OperatingSystem object that contains the current platform //identifier and version number.
ProcessorCount: Knowing the number of processors on the machine will help you take advantage of multiprocessing. This property will help you discover that value.
//Gets the number of processors on the current machine.
Console .WriteLine( "The number of processors on this computer is {0}." ,
StackTrace: This method is very handy for debugging purposes. The methods are listed in reverse chronological order. One line is listed for each method call in the call stack.
TickCount: This property returns the number of milliseconds that have elapsed since the system started. Since the return value is a 32-bit signed integer, if the system keeps running for quite some time (around 25 days), the tick count will reach int32.MaxValue and jumps to Int32.MinValue which is a negative number, then increment to 0 in about 25 days.
//Gets the number of milliseconds elapsed since the system started.
Console .WriteLine( "The tick count is: {0}" , Environment .TickCount);
UserDomainName: This property returns the network domain name associated with the current user. It first attempts to get the domain name of the Windows NT 4.0 account name for the current user. If that fails, the second attempt will be to get the domain name associated with the user name provided by the UserName property. If that fails, then the host computer name is returned.
//Gets the network domain name associated with the current user.
UserInteractive: This property returns true if the current process is running in a user interactive mode. If it returns false, do not display modal dialogs because there is no GUI with which the user can interact.
//Gets a value indicating whether the current process is running in user
UserName: This property gets the user name of the person who is currently logged on. It can be used to customize a particular application. For example, in a web application, you can check whether this user is part of an admin group. If so, you can provide the user extra privileges with which to access pages that are usually hidden from non-admin users.
//Gets the user name of the person who started the current thread.
Version: This property provides the version of the .NET runtime. Based on the version, you can determine what functionality to use. For example, in version 1.0 of the runtime, you can use the thread methods Suspend and Resume. But in higher versions (such as 2.0), these methods are deprecated. So knowing the runtime version helps you use the functionality that best fits your application.
//Gets a Version object that describes the major, minor, build, and revision
WorkingSet: This property returns a 64-bit integer that contains the amount of physical memory that is mapped to the process context. You can call this property before and after loading a certain dll, which is handy when you want to know which dll is consuming the most memory and take additional steps to improve the performance of your application.
//Gets the amount of physical memory mapped to the process context.
GetCommandLineArguments(): The first element in the string array returned is the executable file name. The following elements contain the remaining command-line arguments. For example:
Test.exe a b c
Means that the array of the command line arguments has the following data:
Test.exe
a
b
c
[0] [1] [2] [3]
//Returns a string array containing the command line arguments for the
GetEnvironmentVariable() and GetEnvironmentVariables(): With these methods, you can retrieve one environment variable (GetEnvironmentVariable()) or a dictionary (key-value pairs) of all the environment variables (GetEnvironmentVariables()). You can also use the SetEnvironmentVariable() method to create, modify, or delete an environment variable.
//Retrieves all environment variable names and their values from the
//current process. The return type is a dictionary that you can step through //using a foreach loop. Every element is actually a pair of key and value.
GetLogicalDrives(): By retrieving the logical drives, you can (for instance) determine which one represents the flash drive inserted by the user, and take appropriate actions in your application.
//Returns an array of string containing the names of the logical drives
I hope this article served its purpose of making the developer aware of the existence of this class, and what functionality it provides. Many of the methods and properties listed above help the developer customize the application depending upon the environment under which it is running. After all, if the application is running on Windows Vista, it is favorable to adjust the application features and benefit from the cool functionality that Vista provides. The user will appreciate such minor adjustments, and your application will get a thumbs up in the usability engineering arena.