Visual C# 2005 Recipes



A P P L I C AT I O N D E V E L O P M E N T
11
information might precede the application name. Microsoft Windows 2003, Windows NT 4.0, Win-
dows 2000, and Windows XP don't include path information, whereas Windows 98 and Windows ME
do. The GetCommandLineArgs method returns a string array containing the command-line arguments.
This array can be processed in the same way as the string array passed to the Main method, as dis-
cussed at the start of this section. Unlike the array passed to the Main method, the first element in
the array returned by the GetCommandLineArgs method is the filename of the application.

The Code
To demonstrate the access of command-line arguments, the Main method in the following example
steps through each of the command-line arguments passed to it and displays them to the console.
The example then accesses the command line directly through the Environment class.

using System;
namespace Apress.VisualCSharpRecipes.Chapter01
{

class Recipe01_05
{

public static void Main(string[] args)
{

// Step through the command-line arguments.
foreach (string s in args)
{

Console.WriteLine(s);
}
// Alternatively, access the command-line arguments directly.
Console.WriteLine(Environment.CommandLine);

foreach (string s in Environment.GetCommandLineArgs())
{

Console.WriteLine(s);
}
// Wait to continue.
Console.WriteLine("\nMain method complete. Press Enter.");
Console.ReadLine();

}
}
}
Usage
If you execute the Recipe01-05 example using the following command:
Recipe01-05 "one \"two\" three" four 'five six'
the application will generate the following output on the console:
one "two" three
four
'five
six'