Social Enterprise

Working with the environment in .NET

It is often important to know the details of the environment in which an application is running. The System.Environment class makes it easy to get these values. Here's how.

While .NET applications usually reside on a Windows-based machine (Mono provides non-Windows support), the version and other system characters will vary. For instance, you may need to access the current machine's name, folder locations, operating system version, current user name, and so forth. The .NET Framework provides the answers within the Environment class located in the System namespace.

Inside the class

The System.Environment class allows you to retrieve information about the host environment. This includes the following:

  • Command-line arguments
  • Exit codes
  • Environment variable settings
  • Contents of the call stack
  • Time since last system boot
  • Version of the execution engine

You can access these pieces of information via properties and methods contained within the class. Let's look at them before diving into code examples. We begin with the methods available in the System.Environment class:

  • Exit: terminates the current process and sets the process exit code to the specified value. The exit code is passed to the method as an integer.
  • GetCommandLineArgs returns the arguments specified on the command line as an array of string values.
  • GetEnvironmentVariable returns the value of the specified environment variable (as a string) with the environment variable name passed to the method.
  • GetEnvironmentVariables returns all environment variables and their current settings as an IDictionary object.
  • In addition, the following properties are available:
  • CommandLine: Read-only string property that returns the data entered on the command line when the current process was started.
  • ExitCode: Read/Write integer property that provides access to a process's exit code. The value of System.Environment.ExitCode is returned if a process doesn't return a value when it exits. Zero is returned if this property isn't set by the application.
  • HasShutdownStarted: Read-only Boolean property that signals whether an application has started the shutdown process.
  • NewLine: Read-only string property returning the newline character for the current platform.
  • StackTrace: Read-only string property returning the current state of the call stack as a string value.
  • TickCount: Read-only integer property returning the milliseconds elapsed since the system started. (It cannot be less than five-hundred.)
  • Version: Read-only property returning the current system version. It's returned as a Version object, along with many other properties.

These properties and methods are easy to utilize in your applications. Let's examine them in action with a few examples.

Operating system version

You may find yourself in situations where knowing the current operating system is important. The next example shows how you may determine it with a breakdown of the value(s) returned.

using System;
namespace BuilderExamples {
class Class1 {
static void Main(string[] args) {
Version v;
Console.WriteLine("The current user is: " + Environment.UserName);
v = Environment.Version;
Console.WriteLine("Build: " + v.Build.ToString());
Console.WriteLine("Master: " + v.Major.ToString());
Console.WriteLine("Minor: " + v.Minor.ToString());
Console.WriteLine("Revision: " + v.Revision.ToString());
} } }

The VB.NET version follows:

Imports System
Module Module1
Sub Main()
Dim v As Version
Console.WriteLine("The current user is: " + Environment.UserName)
v = Environment.Version
Console.WriteLine("Build: " + v.Build.ToString())
Console.WriteLine("Master: " + v.Major.ToString())
Console.WriteLine("Minor: " + v.Minor.ToString())
Console.WriteLine("Revision: " + v.Revision.ToString())
End Sub

The values returned will depend upon your system. I receive a build of 4322, with a master and minor version of one, and 2032 for the revision number on my Windows XP machine. You can refer to the details of the Version object for more information.

Working with carriage returns

Displaying output often requires carriage returns to properly format the output. You may be unaware of the carriage return or new line character for the system, so using the Environment class helps ensure the proper value is utilized. The next example takes advantage of this property.

using System;
namespace BuilderExamples {
class Class1 {
static void Main(string[] args) {
String cr = Environment.NewLine;
String[] test = Environment.GetCommandLineArgs();
for (int x = 0; x < test.Length; x++) {
Console.Write(test[x] + cr);
} } } }

It is a simple example, but it does illustrate how you may utilize the platform's newline setting. While Windows machines are consistent, UNIX systems will be different, so converting to something like Mono will not be a problem. Also, it demonstrates accessing the command-line arguments with the first value in the string array being the program (assembly) name. The VB.NET equivalent follows:

Dim cr As String
Dim test() As String
Dim x As Integer
cr = Environment.NewLine
test = Environment.GetCommandLineArgs()
For x = 0 To (test.Length - 1)
Console.Write(test(x) + cr)
Next x

Inside a stacktrace

You are probably familiar with the contents of a stacktrace when an exception is encountered in an application. A stacktrace entry has the following format:

at FullClassName.MethodName(MethodParms) in FileName:line LineNumber

Here's a breakdown of what this line means:

  • FullClassName: Fully-qualified class name
  • MethodName: Method name
  • MethodParms: List of parameter type/name pairs. Each pair is separated by a comma.
  • FileName: The name of the source file where the MethodName method is declared.
  • LineNumber: The line number in the file containing the source code from MethodName for the instruction that is on the call stack.

The next C# line demonstrates a simple call to reveal a stacktrace when no error occurs:


With the following VB.NET equivalent:


This generates the following output on my test machine (for the VB.NET code):

at System.Environment.GetStackTrace(Exception e)
at System.Environment.GetStackTrace(Exception e)
at System.Environment.get_StackTrace()
at BuilderStackTrace.Module1.Main() in C:\BuilderStackTrace\Module1.vb:line 6

Know your environment

It is often important to know the details of the environment in which an application is running. This includes determining if the system is shutting down, environment variable values, and command-line arguments. The System.Environment class makes it easy to get these values.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox