Accessing System information through Environment in C#

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.

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.

namespace demoApp
{
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));
}
}
}

Leave a Reply