Export (0) Print
Expand All

Command Line Parameters Tutorial

Visual Studio .NET 2003

This tutorial shows how the command line can be accessed and two ways of accessing the array of command line parameters.

Sample Files

See Command Line Parameters Sample to download and build the sample files discussed in this tutorial.

Further Reading

Tutorial

The following examples show two different approaches to using the command line arguments passed to an application.

Example 1

This example demonstrates how to print out the command line arguments.

// cmdline1.cs
// arguments: A B C
using System;

public class CommandLine
{
   public static void Main(string[] args)
   {
       // The Length property is used to obtain the length of the array. 
       // Notice that Length is a read-only property:
       Console.WriteLine("Number of command line parameters = {0}",
          args.Length);
       for(int i = 0; i < args.Length; i++)
       {
           Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
       }
   }
}

Output

Run the program using some arguments like this: cmdline1 A B C.

The output will be:

Number of command line parameters = 3
Arg[0] = [A]
Arg[1] = [B]
Arg[2] = [C]

Example 2

Another approach to iterating over the array is to use the foreach statement as shown in this example. The foreach statement can be used to iterate over an array or over a .NET Framework collection class. It provides a simple way to iterate over collections.

// cmdline2.cs
// arguments: John Paul Mary
using System;

public class CommandLine2
{
   public static void Main(string[] args)
   {
       Console.WriteLine("Number of command line parameters = {0}",
          args.Length);
       foreach(string s in args)
       {
          Console.WriteLine(s);
       }
   }
}

Output

Run the program using some arguments like this: cmdline2 John Paul Mary.

The output will be:

Number of command line parameters = 3
John
Paul
Mary

See Also

C# Tutorials | Collection Classes Tutorial

Show:
© 2014 Microsoft