<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; environment</title>
	<atom:link href="http://www.dijksterhuis.org/tag/environment/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Obtaining System information through Environment.* in C#</title>
		<link>http://www.dijksterhuis.org/obtaining-system-information-through-environment-in-csharp/</link>
		<comments>http://www.dijksterhuis.org/obtaining-system-information-through-environment-in-csharp/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 02:21:09 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[environment]]></category>
		<category><![CDATA[getenvironmentvariables]]></category>
		<category><![CDATA[system.environment]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=142</guid>
		<description><![CDATA[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&#8217;t want to properly clean up.

The Environment List
When a program is executed, it is also passed a list [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>Several bits of basic system related information on the environment, working directory, memory use etc can be retrieved through the <strong>Sytem.Environment</strong> class. The class also contains functions that allow you to quickly terminate your program for when don&#8217;t want to properly clean up.</em></p>
<p><span id="more-142"></span></p>
<p><strong>The Environment List</strong></p>
<p>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.</p>
<p>It is then possible to use an IDictionary iterator to step through each of them as show below:</p>
<pre class="brush: c#">
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(&quot;{0}={1}&quot; , envItem.Key,envItem.Value);
}
}
}
</pre>
<p>Under Unix this will print something like this:</p>
<pre class="brush: c#">
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
</pre>
<p>To obtain a named environmental variable is even simpler by making a call to <em>Environment.GetEnvironmentVariable</em>, this routine returns the value of a named Environment value. It returns null if no such variable is found. I have taken the &#8220;PATH&#8221; variable as this one is defined both under Windows and Unix.</p>
<pre class="brush: c#">
using System;

namespace demo2
{

class MainClass
{
public static void Main(string[] args)
{
string theName,theValue;
theName= &quot;PATH&quot;;
theValue = Environment.GetEnvironmentVariable(theName);
if (theValue != null)
Console.WriteLine(&quot;{0}={1}&quot; , theName,theValue);
else
Console.WriteLine(&quot;Not Found!&quot;);
}
}
}
</pre>
<p><strong>The Current Working Directory</strong></p>
<p>Getting the current working directory of our C# program is as simple as calling <em>Environment.CurrentDirectory</em>.</p>
<pre class="brush: c#">
namespace demo1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(&quot;Working Directory={0}&quot; , Environment.CurrentDirectory);
}
}
}
</pre>
<p>Mono offers an alternative to the above function which returns exactly the same information:</p>
<pre class="brush: c#">
using Mono.Unix;
Console.WriteLine(&quot;Working Directory={0}&quot; , (string) UnixDirectoryInfo.GetCurrentDirectory());
</pre>
<p><strong>Additional Environment information</strong></p>
<p>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.</p>
<pre class="brush: c#">
namespace demo1
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine(&quot;Current Directory={0}&quot;, Environment.CurrentDirectory);      // Current working directory of the program
Console.WriteLine(&quot;CommandLine={0}&quot;, Environment.CommandLine);                 // Command line used to execute the program
Console.WriteLine(&quot;MachineName={0}&quot;, Environment.MachineName);                 // Name of the current machine
Console.WriteLine(&quot;NewLine={0}&quot;, Environment.NewLine);                         // Newline character used by OS, \n for Unix, \n\r for Windows
Console.WriteLine(&quot;OSVersion={0}&quot;, Environment.OSVersion);                     // OS Version
Console.WriteLine(&quot;ProcessorCount={0}&quot;, Environment.ProcessorCount);           // Number of CPU&#039;s in the machine
Console.WriteLine(&quot;StackTrace={0}&quot;, Environment.StackTrace);                   // Prints all functions called in order
Console.WriteLine(&quot;SystemDirectory={0}&quot;, Environment.SystemDirectory);         // Returns the &quot;system&quot; directory of the OS, not valid on Unix
Console.WriteLine(&quot;TickCount={0}&quot;, Environment.TickCount);                     // Number of milliseconds since the system started
Console.WriteLine(&quot;UserDomainName={0}&quot;, Environment.UserDomainName);           // Windows domain, Machine name on Unix
Console.WriteLine(&quot;UserInteractive={0}&quot;, Environment.UserInteractive);         //
Console.WriteLine(&quot;UserName={0}&quot;, Environment.UserName);                       // Current username
Console.WriteLine(&quot;Version={0}&quot;, Environment.Version);                         // C# engine version
Console.WriteLine(&quot;WorkingSet={0}&quot;, Environment.WorkingSet);                   // Memory allocated to the process

// ExpandEnviromentalVariables expands any named variable between %%
Console.WriteLine(&quot;ExpandEnvironentVariables={0}&quot;, Environment.ExpandEnvironmentVariables(&quot;This system has the following path: %PATH%&quot;));

String[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine(&quot;CommandLineArgs={0}&quot;, String.Join(&quot;, &quot;, arguments));

String[] drives = Environment.GetLogicalDrives();
Console.WriteLine(&quot;GetLogicalDrives: {0}&quot;, String.Join(&quot;, &quot;, drives));
}
}
}
</pre>
<p>Below is the output from running this code on both Windows and Mono / Ubuntu:</p>
<pre class="brush: c#">
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
</pre>
<pre class="brush: c#">
Current Directory=C:\Documents and Settings\Sandra\Local Settings\Application Da
ta\Temporary Projects\ConsoleApplication1\bin\Debug
CommandLine=&quot;C:\Documents and Settings\Sandra\Local Settings\Application Data\Te
mporary Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe&quot;
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:\
</pre>
<p>The &#8220;Environment.WorkingSet&#8221; is</p>
<p><strong>On beating a quick exit</strong></p>
<p>To terminate your program, there is the <em>Enviroment.Exit()</em> function. For those who think that is not fast enough, there is also <em>Environment.FailFast(&#8221;reason why&#8221;)</em> which supposedly allows you to exit without the program running any <em>try..finally </em>cleanup code. This last function is not (yet) implemented by Mono, it will throw a <em>System.NotImplementedException</em> exception.</p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/obtaining-system-information-through-environment-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
