November 17th, 2008
Obtaining System information through Environment.* in C# - 0
Several bits of basic system related information on the environment, working directory, memory use etc can be retrieved through the Sytem.Environment class. The class also contains functions that allow you to quickly terminate your program for when don’t want to properly clean up.
The Environment List
When a program is executed, it is also passed a list of current environmental variables (such as HOME, PATH etc). This is the same in both Unix and Windows. The following code example shows how a call to Environment.GetEnvironmentVariables returns all the currently defined variables.
It is then possible to use an IDictionary iterator to step through each of them as show below:
using System;
using System.Collections;
namespace demo1
{
class MainClass
{
public static void Main(string[] args)
{
IDictionary theEnv = Environment.GetEnvironmentVariables();
foreach(DictionaryEntry envItem in theEnv)
Console.WriteLine("{0}={1}" , envItem.Key,envItem.Value);
}
}
}
Under Unix this will print something like this:
USERNAME=martijn HOME=/home/nis/martijn DESKTOP_SESSION=gnome PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games LANG=en_US.UTF-8
To obtain a named environmental variable is even simpler by making a call to Environment.GetEnvironmentVariable, this routine returns the value of a named Environment value. It returns null if no such variable is found. I have taken the “PATH” variable as this one is defined both under Windows and Unix.
using System;
namespace demo2
{
class MainClass
{
public static void Main(string[] args)
{
string theName,theValue;
theName= "PATH";
theValue = Environment.GetEnvironmentVariable(theName);
if (theValue != null)
Console.WriteLine("{0}={1}" , theName,theValue);
else
Console.WriteLine("Not Found!");
}
}
}
The Current Working Directory
Getting the current working directory of our C# program is as simple as calling Environment.CurrentDirectory.
namespace demo1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Working Directory={0}" , Environment.CurrentDirectory);
}
}
}
Mono offers an alternative to the above function which returns exactly the same information:
using Mono.Unix;
Console.WriteLine("Working Directory={0}" , (string) UnixDirectoryInfo.GetCurrentDirectory());
Additional Environment information
The following code explores the various members of the Environment class. The interesting information is probably not in the interface but in the different responses that are returned by the Windows Visual C# encoded version and Mono.
namespace demo1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Current Directory={0}", Environment.CurrentDirectory); // Current working directory of the program
Console.WriteLine("CommandLine={0}", Environment.CommandLine); // Command line used to execute the program
Console.WriteLine("MachineName={0}", Environment.MachineName); // Name of the current machine
Console.WriteLine("NewLine={0}", Environment.NewLine); // Newline character used by OS, \n for Unix, \n\r for Windows
Console.WriteLine("OSVersion={0}", Environment.OSVersion); // OS Version
Console.WriteLine("ProcessorCount={0}", Environment.ProcessorCount); // Number of CPU's in the machine
Console.WriteLine("StackTrace={0}", Environment.StackTrace); // Prints all functions called in order
Console.WriteLine("SystemDirectory={0}", Environment.SystemDirectory); // Returns the "system" directory of the OS, not valid on Unix
Console.WriteLine("TickCount={0}", Environment.TickCount); // Number of milliseconds since the system started
Console.WriteLine("UserDomainName={0}", Environment.UserDomainName); // Windows domain, Machine name on Unix
Console.WriteLine("UserInteractive={0}", Environment.UserInteractive); //
Console.WriteLine("UserName={0}", Environment.UserName); // Current username
Console.WriteLine("Version={0}", Environment.Version); // C# engine version
Console.WriteLine("WorkingSet={0}", Environment.WorkingSet); // Memory allocated to the process
// ExpandEnviromentalVariables expands any named variable between %%
Console.WriteLine("ExpandEnvironentVariables={0}", Environment.ExpandEnvironmentVariables("This system has the following path: %PATH%"));
String[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine("CommandLineArgs={0}", String.Join(", ", arguments));
String[] drives = Environment.GetLogicalDrives();
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
}
}
}
Below is the output from running this code on both Windows and Mono / Ubuntu:
Current Directory=/home/nis/martijn/demo1/demo1/bin/Debug CommandLine=/home/nis/martijn/demo1/demo1/bin/Debug/demo1.exe MachineName=dhaka NewLine= OSVersion=Unix 2.6.24.21 ProcessorCount=2 StackTrace= at System.Environment.get_StackTrace() at demo1.MainClass.Main(System.String[] args) in /home/nis/martijn/demo1/demo1/Main.cs:line 20 SystemDirectory= TickCount=1626622851 UserDomainName=dhaka UserInteractive=False UserName=martijn Version=2.0.50727.42 WorkingSet=0 ExpandEnvironentVariables=This system has the following path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games CommandLineArgs=/home/nis/martijn/demo1/demo1/bin/Debug/demo1.exe GetLogicalDrives: /, /sys, /mnt/backup
Current Directory=C:\Documents and Settings\Sandra\Local Settings\Application Da ta\Temporary Projects\ConsoleApplication1\bin\Debug CommandLine="C:\Documents and Settings\Sandra\Local Settings\Application Data\Te mporary Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe" MachineName=DHAKA-XP NewLine= OSVersion=Microsoft Windows NT 5.1.2600 Service Pack 2 ProcessorCount=1 StackTrace= at System.Environment.GetStackTrace(Exception e, Boolean needFileI nfo) at System.Environment.get_StackTrace() at demo1.MainClass.Main(String[] args) in C:\Documents and Settings\Sandra\Lo cal Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs: line 18 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySec urity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, C ontextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() SystemDirectory=C:\WINDOWS\system32 TickCount=8790984 UserDomainName=DHAKA-XP UserInteractive=True UserName=Martijn Version=2.0.50727.3053 WorkingSet=18067456 ExpandEnvironentVariables=This system has the following path: C:\WINDOWS\system3 2;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\QuickTime\QTSystem\ CommandLineArgs=C:\Documents and Settings\Sandra\Local Settings\Application Data \Temporary Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe GetLogicalDrives: A:\, C:\, D:\
The “Environment.WorkingSet” is
On beating a quick exit
To terminate your program, there is the Enviroment.Exit() function. For those who think that is not fast enough, there is also Environment.FailFast(”reason why”) which supposedly allows you to exit without the program running any try..finally cleanup code. This last function is not (yet) implemented by Mono, it will throw a System.NotImplementedException exception.
Tags: environment, getenvironmentvariables, system.environment









Except where otherwise noted, content on this site is