[Previous] [Contents] [Next]

Command-Line Arguments

You can access the command-line arguments to an application by declaring the Main method as taking a string array type as its only argument. At that point, the arguments can be processed as you would any array. Although arrays won't be covered until Chapter 7, here's some generic code for iterating through the command-line arguments of an application and writing them out to the standard output device: -

using System;
class CommandLineApp
{
    public static void Main(string[] args)
    {
        foreach (string arg in args)
        {
            Console.WriteLine("Argument: {0}", arg);
        }
    }
}

And here's an example of calling this application with a couple of randomly selected values: -

e:>CommandLineApp 5 42
Argument: 5
Argument: 42

The command-line arguments are given to you in a string array. To process the parameters as flags or switches, you'll have to program that capability yourself.

NOTE
Developers in Microsoft Visual C++ are already accustomed to iterating through an array that represents the command-line arguments to an application. However, unlike Visual C++, the array of command-line arguments in C# does not contain the application name as the first entry in the array.

[Previous] [Contents] [Next]