Read Command Line Parameters In Console Application

whenever you need to make a small application to test some library or a Peace of code or your application does not even need to have a GUI , you may need to deal with a parameters sent to your application .

Command line parameters are sent to the application as an array of string(string[]) and there is 2 ways that you can use to access this array to get parameters values , assuming that your exe file is called cApp and is called from command line like :

>cApp a1 a2 a3

The first way to read the array is using for statement

using System;

public class cApp
{
    public static void Main(string[] args)
    {
        // Display the number of parameters sent to the application 
        Console.WriteLine("Parameters Count = {0}", args.Length);

        // Display Parameters values
        for(int i = 0; i < args.Length; i++)
        {
            Console.WriteLine("args[{0}] = [{1}]", i, args[i]);
        }
    }
}
 

The result will be like :

>Parameters Count = 3
>args[0] = [a1]
>args[1] = [a2]
>args[2] = [a3]


The second way to read the array using foreach statement like the following :

using System;

public class cApp
{
   public static void Main(string[] args)
   {
        // Display the number of parameters sent to the application 
        Console.WriteLine("Parameters Count = {0}", args.Length);
      
        // Display Parameters values
        foreach(string str in args)
        {
            Console.WriteLine(str);
        }
   }
}
 
The result will be like :

>Parameters Count = 3
>a1
>a2
>a3

No comments:

Post a Comment